您的位置:首页 > 其它

连续子数组求和-LintCode

2017-10-10 09:18 369 查看
给定一个整数数组,请找出一个连续子数组,使得该子数组的和最大。输出答案时,请分别返回第一个数字和最后一个数字的下标。(如果两个相同的答案,请返回其中任意一个)

样例:

给定 [-3, 1, 3, -3, 4], 返回[1,4].

#ifndef C402_H
#define C402_H
#include<iostream>
#include<vector>
using namespace std;
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> res;
if (A.empty())
return res;
res.push_back(0);
res.push_back(0);
int len = A.size();
int sum = 0, max = INT_MIN;
int start = 0, end = 0;
for (int i = 0; i < len; ++i)
{
if (sum >= 0)
{
sum += A[i];
end = i;
}
else
{
sum = A[i];
start = end = i;
}
if (sum > max)
{
max = sum;
res[0] = start;
res[1] = end;
}
}
return res;
}
};
#endif
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: