Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 53. Maximum Subarray

Rain Hu

53. Maxmimum Subarray


一、題目

Given an integer array num, find the subarray with the largest sum, and return its sum.

Example 1:

Example 2:

Example 3:

Constraints:

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.


二、分析

三、解題

1. DP

int maxSubArray(vector<int>& nums) {
    int res = nums[0];
    // int curr = INT_MIN;
    vector<int> dp(nums.size(), 0);
    dp[0] = nums[0];
    for (int i = 1; i < nums.size(); i++) {
        dp[i] = max(nums[i], nums[i] + dp[i-1]);
        res = max(dp[i], res);
    }
    return res;
}

2. DP(space optimized)

int maxSubArray(vector<int>& nums) {
    int curr = INT_MIN, res = INT_MIN;
    for (const auto& x : nums) {
        curr = curr < 0 ? x : curr + x;
        res = max(res, curr);
    }
    return res;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 974. Subarray Sums Divisible by K
Next
[LeetCode] 918. Maximum Sum Circular Subarray