给定一个整数数组,请找出一个连续子数组,使得该子数组的和最大。输出答案时,请分别返回第一个数字和最后一个数字的值。(如果两个相同的答案,请返回其中任意一个)
class Solution { public: /** * @param A an integer array * @return A list of integers includes the index of * the first number and the index of the last number */ vector<int> continuousSubarraySum(vector<int>& A) { // Write your code here vector<int> result; int n = A.size(); if (n < 1) { return result; } int begin = 0; int end = 0; int sum = A[0]; int maxSum = A[0]; int maxBegin = 0; int maxEnd = 0; for (int i = 1; i < n; i++) { if (sum <= 0) { if (A[i] > sum) { begin = i; end = i; sum = A[i]; } if (A[i] >= maxSum) { maxBegin = i; maxEnd = i; maxSum = A[i]; } } else { sum += A[i]; if (sum > 0) { end = i; } if (sum > maxSum) { maxBegin = begin; maxEnd = i; maxSum = sum; } } } result.push_back(maxBegin); result.push_back(maxEnd); return result; } };