1. 程式人生 > >最大子數組

最大子數組

com n-1 begin logs 子數組 mage indicate array es2017

技術分享

class Solution {
public:
  /*
  * @param nums: A list of integers
  * @return: A integer indicate the sum of max subarray
  */
  int maxSubArray(vector<int> &nums) {
    // write your code here
  int sum = 0, flag = 0,n=nums.size();
  for (int i = 0; i < n; i++) {
    flag += nums[i];
    if (flag < 0) flag = 0;
    if (flag > sum) sum = flag;
  }
  sort(nums.begin(), nums.end());
  if (nums[n-1] <= 0) {
    sum = nums[n-1];
  }
  return sum;
  }
};

最大子數組