[Leetcode] Maximum Subarray

Maximum Subarray 题解

题目来源:https://leetcode.com/problems/maximum-subarray/description/


Description

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

Example

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.

Solution


class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        if (nums.empty())
            return 0;
        int size = nums.size();
        vector<int> dp(size, 0);
        dp[0] = nums[0];
        int max = dp[0];
        for (int i = 1; i < size; i++) {
            dp[i] = (dp[i - 1] > 0 ? dp[i - 1] : 0) + nums[i];
            if (dp[i] > max)
                max = dp[i];
        }
        return max;
    }
};


解题描述

这道题的题意是,对给出的一个数组,求其所有连续区间的最大和。上面给出的解法是使用的是DP,从左向右扫描一遍数组,每一步的问题是:

  • 记最终最大和结果为max,初始值为dp[0]
  • 记当前数组元素为nums[i]
  • 当前数组元素之前的数组区间的临时最大和为dp[i - 1]
    • 如果dp[i - 1]为负,则没有必要加到区间[0, i]的临时最大和上,反之则加上
    • 区间[0, i]的临时最大和为dp[i] = (dp[i - 1] > 0 ? dp[i - 1] : 0) + nums[i]
  • 如果当前临时最大和大于max,则max替换为该值
原文地址:https://www.cnblogs.com/yanhewu/p/8371524.html