给定一个整数数组,请找出一个连续子数组,使得该子数组的和最大。输出答案时,请分别返回第一个数字和最后一个数字的下标。(如果两个相同的答案,请返回其中任意一个)
样例
给定 [-3, 1, 3, -3, 4]
, 返回[1,4]
.
如果数组全为负数,则选择其最大的即可。
否则偏历一次,记录以下标i结尾的最大和子数组,如果当前子数组的和小于0,则更新子数组头(即 tb = i+1);如果当前子数组的和比 下标为0--i-1的数组中的最大和大,则更新最大和及其范围。
代码:
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) {
// Write your code here
int Rb,Re,Max,tb,ts,MaxId;
Max = Integer.MIN_VALUE;
MaxId = Rb = Re = ts = tb = 0;
for(int i=0;i<A.length;++i){
ts += A[i];
if(ts < 0){
tb = i+1;
ts = 0;
}else if(ts > Max){//更新最大和及其范围
Rb = tb;
Re = i;
Max = ts;
}
if(A[i] > A[MaxId])
MaxId = i;
}
if(Rb==0&&Re==0)
Rb = Re = MaxId;
ArrayList<Integer> R = new ArrayList<Integer>();
R.add(Rb);
R.add(Re);
return R;
}
}