本程式碼可以通過以下測試用例:

陣列:[1,-2,3,5,-3,2] 返回:8

陣列:[0,-2,3,5,-1,2] 返回:9

陣列:[-9,-2,-3,-5,-3] 返回:-2

程式碼清單如下:

#include <iostream>
using namespace std;

int maxSum(int* arr,int n)
{
	int sum=0,max=arr[0];
	for(int i=0;i<n;i++)
	{
		sum+=arr[i];
		max=(max>sum) ? max: sum;
		if(sum<0)
			sum=0;
	}
	return max;
}
int main()
{
	int arr[]={-9,-2,-3,-5,-32};
	int n;
	n=sizeof(arr)/sizeof(arr[0]);	
	cout<<maxSum(arr,n)<<endl;
	return 0;
}

擴充套件問題2.同時返回最大子陣列的位置。

#include <iostream>
using namespace std;

int maxSum(int* arr,int n,int* start,int* end)
{
	int sum=0,max=arr[0];
	int sum_start=0,sum_end=0;
	for(int i=0;i<n;i++)
	{
		sum+=arr[i];
		if(sum>=0)//更新sum_end,得到sum求和的陣列範圍
			sum_end=i;
		if(max<sum)
		{
			max=sum;
			*start=sum_start;
			*end=sum_end;
		}
		if(sum<0)
		{
			sum=0;
			sum_start=sum_end=i+1;//重置sum的範圍
		}		
	}
	return max;
}
int main()
{
	int arr1[]={-9,-2,-3,-5,-32};
	int arr2[]={0,-2,3,5,-1,2};
	int arr[]={1,-2,3,5,-3,2};
	int start=-1,end=-1;
	int n;
	n=sizeof(arr)/sizeof(arr[0]);	
	cout<<maxSum(arr,n,&start,&end)<<endl;
	cout<<"start: "<<start<<" end: "<<end<<endl;
	return 0;
}