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 A = [-3, 1, 3, -3, 4], return [1,4].

分析:

max(i) = {max(i - 1) + A[i] if max(i - 1) >= 0, otherwise, A[i]}

 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
* cnblogs.com/beiyeqingteng/
*/
public ArrayList<Integer> continuousSubarraySum(int[] A) {
if (A == null || A.length == ) return null; ArrayList<Integer> list = new ArrayList<Integer>();
// initialization
int preMax = A[];
int startIndex = ;
int tempMax = A[];
list.add();
list.add(); for (int i = ; i < A.length; i++) {
if (preMax < ) {
preMax = A[i];
startIndex = i;
} else {
preMax = A[i] + preMax;
}
// update
if (preMax > tempMax) {
list.clear();
list.add(startIndex);
list.add(i);
tempMax = preMax;
}
}
return list;
}
}

转载请注明出处:cnblogs.com/beiyeqingteng/

上一篇:TDDL与Spring Boot集成Version报错——跟踪与解决


下一篇:用T4 Template生成代码