[LintCode] Continuous Subarray Sum

来源:互联网 发布:网络女神成路人 贴吧 编辑:程序博客网 时间:2024/05/16 15:07

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;    }};
0 0
原创粉丝点击