推荐http://shmilyaw-hotmail-com.iteye.com/blog/1616632
给定(可能是负的)整数序列A1, A2,...,AN, 寻找(并标识)使Sum(Ak)(k >=i, k <= j)的值最大的序列。如果所有的整数都是负的,那么连续子序列的最大和是零。
#include <iostream> using namespace std; int max(int a,int b){ return a>b?a:b; } //max[i]=max{a[i],a[i]+max[i-1} void calc(int arr[],int n){ int sum; if(arr[0]<0) sum = 0; else sum = arr[0]; for(int i=1;i<n;i++){ sum = max(arr[i],arr[i]+sum); } cout<<"max value:"<<sum<<endl; } int main(){ //int arr[]={5,-2,3,4,-7,2};//1680 int arr[]={5,-2,3,4,1,2};//24 int n = 6; calc(arr,n); return 0; }