Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [?2,1,?3,4,?1,2,1,?5,4]
,
the contiguous subarray [4,?1,2,1]
has the largest sum = 6
.
给定一个数组,找出和最大的子数组,返回这个最大和
class Solution { public: int maxSubArray(int A[], int n) { if(n==0)return 0; if(n==1)return A[0]; int max=A[n-1]; int*maxSum=new int[n]; maxSum[n-1]=A[n-1]; for(int i=n-2; i>=0; i--){ if(maxSum[i+1]<0)maxSum[i]=A[i]; else maxSum[i]=A[i]+maxSum[i+1]; if(maxSum[i]>max)max=maxSum[i]; } return max; } };
LeetCode: Maximum Subarray [052],布布扣,bubuko.com
LeetCode: Maximum Subarray [052]
原文地址:http://blog.csdn.net/harryhuang1990/article/details/26736009