[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
return
思路:如果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;
}
}
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;
}
}
相关文章推荐
- Continuous Subarray Sum
- Continuous Subarray Sum
- Continuous Subarray Sum
- 算法训练:Continuous Subarray Sum
- [LeetCode] Continuous Subarray Sum
- 523. Continuous Subarray Sum
- 523. Continuous Subarray Sum
- lintcode-medium-Continuous Subarray Sum
- lintcode:Continuous Subarray Sum
- [LintCode] Continuous Subarray Sum
- 523. Continuous Subarray Sum
- lintcode-Continuous Subarray Sum
- 算法15 Continuous Subarray Sum
- Continuous Subarray Sum II
- [LeetCode]Continuous Subarray Sum
- 523. Continuous Subarray Sum
- 523-Continuous Subarray Sum
- LintCode "Continuous Subarray Sum II"
- [LintCode] Continuous Subarray Sum II
- 523. Continuous Subarray Sum