(LeetCode OJ) Maximum Subarray [53]
53. Maximum Subarray
My Submissions QuestionTotal Accepted: 89899 Total Submissions: 253014 Difficulty: Medium
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.
Click to show more practice.
Subscribe to see which companies asked this question
Hide Tags Divide and Conquer Array Dynamic Programming Show Similar Problems
// Typical dynamic planning problem: // train of thought first: // obviously, nums [I] is added in the continuous accumulation process. If sum is less than 0, so it indicates the side effects of the previous sums calculation. You need to re-find the starting value and start accumulating. // you need to re-start accumulating class Solution {public: int maxSubArray (vector
& Nums) {int maxSum = nums [0]; // The maximum value int subSum = nums [0]; for (int I = 1; I <nums. size (); I ++) {subSum = subSum <= 0? Nums [I]: subSum + nums [I]; if (subSum> maxSum) maxSum = subSum ;}return maxSum ;}};