1. 程式人生 > >LeetCode [53. Maximum Subarray]

LeetCode [53. Maximum Subarray]

Question

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

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.

思路

  1. 動態規劃
    狀態方程: sum(i) = max{ sum(i-1)+a(i), a(i) }
    sum(i)是以i結尾和最大的連續子序列,a(i)是陣列的第i個值
  2. 從第一個數開始,往後一直累加,如果累加的和小於0,則重新從下一個位置開始累加,不斷更新最大值。

程式碼

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

比較直接簡單的程式碼

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int cursum = 0;
        int ans = nums[0];
        for
(int i = 0; i < nums.size(); i++) { cursum += nums[i]; ans = max(cursum, ans); cursum = max(cursum, 0); } return ans; } };