输入:
[1,-2,3,10,-4,7,2,-5]
返回值:
[3,10,-4,7,2]
说明:
经分析可知,输入数组的子数组[3,10,-4,7,2]可以求得最大和为18,故返回[3,10,-4,7,2]
import java.util.*;
public class Solution {
public int[] FindGreatestSumOfSubArray (int[] array) {
//记录到下标i为止的最大连续子数组和
int[] dp = new int[array.length];
dp[0] = array[0];
int maxsum = dp[0];
//滑动区间
int left = 0, right = 0;
//记录最长的区间
int resl = 0, resr = 0;
for(int i = 1; i < array.length; i++){
right++;
//状态转移:连续子数组和最大值
dp[i] = Math.max(dp[i - 1] + array[i], array[i]);
//区间新起点
if(dp[i - 1] + array[i] < array[i])
left = right;
//更新最大值
if(dp[i] > maxsum || dp[i] == maxsum && (right - left + 1) > (resr - resl + 1)){
maxsum = dp[i];
resl = left;
resr = right;
}
}
//取数组
int[] res = new int[resr - resl + 1];
for(int i = resl; i <= resr; i++)
res[i - resl] = array[i];
return res;
}
}