[Leetcode] Maximum Subarray

Posted 言何午

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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替换为该值

以上是关于[Leetcode] Maximum Subarray的主要内容,如果未能解决你的问题,请参考以下文章

[Leetcode] Maximum Subarray

[LeetCode]Maximum Subarray

#Leetcode# 53. Maximum Subarray

LeetCode 53. Maximum Subarray

LeetCode -- Maximum Product Subarray

leetcode 53. Maximum Subarray