Leetcode_53_Maximum Subarray
Opened this issue · 0 comments
lihe commented
Maximum Subarray
Given an integer array nums
, find the contiguous subarray
(containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n)
solution, try coding another solution using the divide and conquer approach, which is more subtle.
分析:将求n
个数的数组的最大子段和转化为分别求出以第1
个、第2
个...第n
个数字结尾的最大子段和,再找出这n
结果中最大的,即为结果。
算法思路:
dp[i]
为以第i
个数字结尾的最大子段和;- 若
dp[i-1] > 0
则dp[i] = dp[i-1] + nums[i]
,否则dp[i] = nums[i]
; - 边界值
dp[0] = nums[0]
。
class Solution{
public:
int maxSubArray(std::vector<int> &nums){
std::vector<int> dp(nums.size(), 0);
dp[0] = nums[0];
int max_res = dp[0];
for(int i = 1; i < nums.size(); i++){
dp[i] = std::max(dp[i - 1] + nums[i], nums[i]);
if(max_res < dp[i]){
max_res = dp[i];
}
}
return max_res;
}
};