[Amazon] Continuous Subarray Sum

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)

Example

Give [-3, 1, 3, -3, 4], return [1,4].

思路:如果curSum<0,start和end index都要重置爲當前位置(因爲curSum<0是因爲加了一些負數,或者一開始是負數)

           如果curSum>=0,更新end爲當前位置

          當maxVal<curSum的時候,更新curSum,並更新result list裏兩個位置的值

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<>();
        if(A==null || A.length==0){
            return result;
        }
        result.add(0);
        result.add(0);
        
        int curSum=0;
        int maxVal=Integer.MIN_VALUE;
        int start=0;
        int end=0;
        for(int i=0;i<A.length;i++){
            if(curSum<0){
                curSum=A[i];
                start=end=i;
            }else{
                curSum+=A[i];
                end=i;
            }
            
            if(maxVal<curSum){
                maxVal=curSum;
                result.set(0,start);
                result.set(1,end);
            }
        }
        return result;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章