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

[leetcode] 53. Maximum Subarray

nta span ber con 可能 public with tro bar

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; } };

[leetcode] 53. Maximum Subarray