Continuous Subarray Sum

Description

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 the minimum one in lexicographical order)

 

Example

Example 1:

Input: [-3, 1, 3, -3, 4]
Output: [1, 4]

Example 2:

Input: [0, 1, 0, 1]
Output: [0, 3]
Explanation: The minimum one in lexicographical order.
思路:

枚举即可, 枚举的过程中维护以当前元素结尾的最大和.

每次循环把当前元素加到这个和中, 在加上之前判断:

  • 如果这个和是负数, 则放弃之前的元素, 把和置为0, 区间左端点设为当前元素
  • 如果是正数, 则直接累加.

同时, 在枚举的过程中维护答案.

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<Integer> continuousSubarraySum(int[] A) {
        ArrayList<Integer> result = new ArrayList<Integer>();
        result.add(0);
        result.add(0);

        int len = A.length;
        int start = 0, end = 0;
        int sum = 0;
        int ans = -0x7fffffff;
        for (int i = 0; i < len; i++) {
            if (sum < 0) {
                sum = A[i];
                start = end = i;
            } else {
                sum += A[i];
                end = i;
            }
            if (sum > ans) {
                ans = sum;
                result.set(0, start);
                result.set(1, end);
            }
        }
        return result;
    }
}

  

posted @ 2019-12-21 22:24  YuriFLAG  阅读(156)  评论(0)    收藏  举报