您的位置:首页 > 其它

[LintCode] Continuous Subarray Sum

2015-11-09 10:17 387 查看
Given an integer array, find a continuous subarray where the sum of numbers is the biggest. Your code should return the index of the first number and the index of the last number. (If their are duplicate answer, return anyone)

For this problem, we first need to track subarray’s start point, and the maxSum. O(n) time complexity.

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