最大字数组问题是递归与分治算法中的经典问题:
问题:求一个数组中相加可以获得最大值的子数组,子数组是指原数组中任意连续的一段
代码:
#include <iostream> using namespace std; int max_mid(int *a,int mid,int low,int high) { int ml = a[mid]; int mr = 0; int sum = ml; for(int i = mid-1; i>=low; i--) { sum = sum+a[i]; if(sum>ml) { ml = sum; } } sum = 0; for(int i = mid+1; i<=high; i++) { sum = sum+a[i]; if(sum>mr) { mr = sum; } } return ml+mr; } int max(int *a,int low,int high) { if(low == high) { return a[low]; } else { int mm; int ml; int mr; int mid = (low+high)/2; ml = max(a,low,mid); mm = max_mid(a,mid,low,high); mr = max(a,mid+1,high); if(mm>=ml&&mm>=mr) { return mm; } if(ml>=mm&&ml>=mr) { return ml; } else { return mr; } } } int a[1000]; int main() { int n; while(cin>>n) { for(int i = 0; i<n; i++) { cin>>a[i]; } cout<<max(a,0,n-1)<<endl; } return 0; }
本文出自 “开发者” 博客,请务必保留此出处http://tang1513.blog.51cto.com/7678175/1566341
原文地址:http://tang1513.blog.51cto.com/7678175/1566341