您的位置:首页 > 其它

[Amazon] Continuous Subarray Sum

2017-07-14 10:56 218 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: