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(vector<int>& nums) { int size = nums.size(); int* dp = new int[size+1]; dp[0] = 0; for(int i=1;i<size+1;i++){ dp[i] = max(dp[i-1]+nums[i-1],nums[i-1]); } int res = INT_MIN; for(int i=1;i<size+1;i++){ res = max(res,dp[i]); } return res; } };