Continuous Subarray Sum(连续子数组求和)

http://www.lintcode.com/zh-cn/problem/continuous-subarray-sum/?rand=true

import java.util.ArrayList;

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 ArrayList continuousSubarraySum(int[] A) {
        // Write your code here
        int max = Integer.MIN_VALUE;
        int sum = 0;
        ArrayList list = new ArrayList();
        int end = 0;
        int start = 0;
        list.add(0);
        list.add(0);
        for (int i = 0; i < A.length; i++) {
            if (sum < 0) {
//                如果小于0,这段数组加上只会起反作用,所以直接删除
                sum = 0;
                start = i;
            }
            sum += A[i];
            end = i;
            if (sum > max) {
                max = sum;
                list.set(0, start);
                list.set(1, end);
            }
        }
        return list;
    }
}

你可能感兴趣的:(Continuous Subarray Sum(连续子数组求和))