题解 | #连续子数组的最大和(二)#
连续子数组的最大和(二)
http://www.nowcoder.com/practice/11662ff51a714bbd8de809a89c481e21
关键在于引入双指针帮助存储最大序列的坐标
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param array int整型一维数组
* @return int整型一维数组
*/
public int[] FindGreatestSumOfSubArray (int[] array) {
// write code here
if(array.length == 1){
int[] res = new int[1];
res[0] = array[0];
return res;
}
ArrayList<Integer> list = new ArrayList<>();
list.add(array[0]);
int max = array[0],left = 0,right = 0,snapLift=0,snapRight=0,maxLengh=0;
for(int i=0;i<array.length-1;i++){
right++;
list.add(Math.max(list.get(i)+array[i+1],array[i+1]));
if(list.get(i)+array[i+1]<array[i+1]){
left = right;
}
if(list.get(i+1)>max || list.get(i+1) == max && right-left+1>maxLengh){
snapLift = left;
snapRight = right;
maxLengh = right - left + 1;
max = list.get(i+1);
}
}
int[] res = new int[maxLengh];
int index =0;
for(int p=snapLift;p<=snapRight;p++){
res[index++] = array[p];
}
return res;
}
}