首页 > 代码库 > [LeetCode] Maximum Subarray

[LeetCode] Maximum Subarray

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.

查找给定数组中连续子数组最大的和。连续相加数组中的元素知道和小于0,如果这个和为负数,就让sum = 0,相当于抛弃了前面的子数组。

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int res = INT_MIN, sum = 0;
        for (int num : nums) {
            sum += num;
            res = max(res, sum);
            sum = max(sum, 0);
        }
        return res;
    }
};
// 9 ms

这是一个最优化问题,所以可以使用动态规划的方法求解,首先需要找出子问题关系表达式,dp数组表示最大子数组的结束。dp[i] = nums[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0).

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

 

[LeetCode] Maximum Subarray