1. 程式人生 > >[Leetcode] Maximum Subarray

[Leetcode] Maximum Subarray

大於 max log logs with con 個數 連續 描述

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