lihe/Leetcode

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结果中最大的,即为结果。

算法思路:

  1. dp[i]为以第i个数字结尾的最大子段和;
  2. dp[i-1] > 0dp[i] = dp[i-1] + nums[i],否则dp[i] = nums[i];
  3. 边界值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;
    }
};