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


 

只要知道 除非全负,任何的负的子序列不可能是最优子序列的前缀 就可以了。

我的代码:

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

 

相关文章:

  • 2021-12-25
  • 2021-09-16
  • 2021-12-24
  • 2022-12-23
  • 2022-02-05
猜你喜欢
  • 2021-08-31
  • 2021-07-08
  • 2021-08-25
  • 2021-05-21
  • 2021-10-21
  • 2021-06-30
  • 2021-09-13
相关资源
相似解决方案