- Question:
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
.
- Analysis:
这道题求解最大连续子序列和,这可以用枚举法和分治法以及动态规划,使用动态规划解题会更简单于是这里使用的是动态规划。对题目进行解析,状态为子序列,从最左边开始遍历整个序列,每一个子序列有两种情况,一种是和大于0,另一种是和小于等于0,那么序列小于等于0时可以认为是对后面序列和没有贡献的,所以不再加入到后续的序列中。设f[j]为当前状态,表示以D[j]结尾的最大连续子序列和,由此可以得到状态转移方程为:f[j]=max{f[j]+D[j],D[j]}.
- Code:
class Solution { public: int maxSubArray(vector<int>& nums) { int result = INT_MIN; int f = 0; for (int i=0;i<nums.size();i++) { f = max(f+nums[i],nums[i]); result = max(result,f); } return result; } };