连续子数组求和
给定一个整数数组,请找出一个连续子数组,使得该子数组的和最大。输出答案时,请分别返回第一个数字和最后一个数字的值。(如果两个相同的答案,请返回其中任意一个)
您在真实的面试中是否遇到过这个题?
Yes
样例
标签
Expand
给定 [-3, 1, 3, -3, 4]
, 返回[1,4]
.
相关题目
Expand
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
if(A==null||A.length==0) return null;
ArrayList<Integer> res = new ArrayList<>();
int sum = 0;
int len = A.length;
int max = Integer.MIN_VALUE;
int min = 0;
int minPos = -1;
int curminPos = -1;
int maxPos = 0;
for(int i=0;i<len;i++){
sum += A[i];
if(sum-min>max){
minPos = curminPos;
max = sum-min;
maxPos = i;
}
if(min>sum){
min = sum;
curminPos = i;
}
}
res.add(minPos+1);res.add(maxPos);
return res;
}
}