Description
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
Input
[-2,1,-3,4,-1,2,1,-5,4]
Output
6 //the contiguous subarray [4,-1,2,1] has the largest sum = 6.
思路
CLRS 第四章练习题 4.1-5,动态规划 5 mins 过,时间复杂度 O(n) 。
class Solution { public: int maxSubArray(vector<int>& nums) { int dp, sum; dp = nums[0]; sum = nums[0]; for (int i = 1; i < nums.size(); i++) { if (dp > 0) { dp += nums[i]; } else dp = nums[i]; if (dp > sum) sum = dp; } return sum; } };