53. Maximum Subarray
My SubmissionsTotal Accepted: 89899 Total Submissions: 253014 Difficulty: MediumFind 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//典型的動態規劃問題: //思路首先: //很顯然在連續累加的過程中,加了nums[i]如果sum是小於0的,那麼說明前一次計算出的sums其副作用,需要重新尋找起始開始累加 //即重新以當前nums[i]為起始值開始累加 class Solution { public: int maxSubArray(vector& nums) { int maxSum = nums[0];//記錄累加過程中的最大值 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; } };