描述:给定一个整数数组,请找出一个连续子数组,使得该子数组的和最大。输出答案时,请分别返回第一个数字和最后一个数字的下标。(如果存在多个答案,请返回字典序最小的)
思路:ans 记录最大值,sum表示lefg,right间数组和,遍历数组,若sum < 0,则更新left,right值,否则只把right位置更新。然后sum,ans值比较,更新ans值和left,right值
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
int ans = INT_MIN;
int sum = 0;
int left = 0;
int right = 0;
vector<int> ints(2,0);
//ans 记录最大值,sum表示lefg,right间数组和,遍历数组,若sum < 0,则更新left,right值,否则只把right位置更新。
//然后sum,ans值比较,更新ans值和left,right值
for( int i = 0; i < A.size(); ++i )
{
if( sum < 0 )
{
sum = A[i];
left = right = i;
}
else
{
sum += A[i];
right = i;
}
if( sum > ans )
{
ans = sum;
ints[0] = left;
ints[1] = right;
}
}
return ints;
}
};