【三次过】Lintcode 402. 连续子数组求和

给定一个整数数组,请找出一个连续子数组,使得该子数组的和最大。输出答案时,请分别返回第一个数字和最后一个数字的下标。(如果存在多个答案,请返回字典序最小的)

样例

样例 1:

输入: [-3, 1, 3, -3, 4]
输出: [1, 4]

样例 2:

输入: [0, 1, 0, 1]
输出: [0, 3]
解释: 字典序最小.

解题思路:

我们用sum来记录当前位置的累计和,如果某一个位置之前的累计和为负数,那么我们直接从当前位置开始重新算即可,因为加上负数还不如不加,此时将l 和r 都更新为当前位置i;如果之前的累计和大于等于0,那么我们把累计和sum再加上当前的数字,然后更新r 位置为i。此时我们更新最大子数组之和ans,以及res即可

public class Solution {
    /*
     * @param A: An integer array
     * @return: A list of integers includes the index of the first number and the index of the last number
     */
    public List continuousSubarraySum(int[] A) {
        // write your code here
        List res = new ArrayList<>(2);
        res.add(0);
        res.add(0);
        
        int sum = 0;                    //暂存以当前i为结尾的和
        int ans = Integer.MIN_VALUE;    //最大和
        int l = 0;                      //连续子数组的左边界
        int r = 0;                      //连续子数组的右边界
        
        for(int i=0; i ans){
                ans = sum;
                res.set(0, l);
                res.set(1, r);
            }
        }
        
        return res;
    }
}

 

你可能感兴趣的:(lintcode,数组)