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
.
思路:
动态规划
由[-2, 1,-3, 4,-1, 2, 1,-5, 4]可得其dp数组,
为[-2, 1,-2, 4, 3, 5, 6, 1, 5]。
即其状态转移过程为:
if (dp[i-1]>0) dp[i] = nums[i] + dp[i-1]; else dp[i] = nums[i] + 0;
code:
动规:
class Solution { public: int maxSubArray(vector<int>& nums) { int len = nums.size(); if(0==len) return 0; vector<int> dp(len); dp[0]=nums[0]; int res=nums[0]; for(int i=1;i<len;i++) { dp[i] = nums[i] + (dp[i-1] > 0 ? dp[i-1]:0); res = dp[i] > res? dp[i] :res; } return res; } };
class Solution { public: int maxSubArray(vector<int>& nums) { int len = nums.size(); if(0==len) return 0; int dp = nums[0]; int res = dp; for(int i = 1; i<len; i++) { dp = nums[i] + (dp > 0 ? dp : 0); res = dp > res ? dp : res; } return res; } };