当一个数组有负数时,最大子数组才会有意义。
package shu.quan.demo;
/**
* 求最大子串的值,并求出脚标。
*/
public class MaxSubsequence {
static int ileft = 0, iright = 0;
public static void main(String[] args){
int[] arr = new int[]{1,5,-5,6,-13,4,8,-5,14};
int res = maxSubsequence(arr);
System.out.print("["+ileft+","+iright+"]"+res);
}
static int maxSubsequence(int[] arr){
return maxSubsequence(arr,0,arr.length - 1);
}
static int maxSubsequence(int[] arr, int left, int right){
if(left == right){
return arr[left];
}else {
int center = (left + right) /2;
int maxLeftSum = maxSubsequence(arr, left, center);
int maxRightSum = maxSubsequence(arr, center + 1, right);
int maxLeftSubsequenceSum = 0, maxLeft = 0;
for (int i = center; i >= left; i--) {
maxLeftSubsequenceSum += arr[i];
if (maxLeftSubsequenceSum > maxLeft){
maxLeft = maxLeftSubsequenceSum;
ileft = i;
}
}
int maxRightSubsequenceSum = 0, maxRight = 0;
for (int i = center + 1; i <= right; i++) {
maxRightSubsequenceSum += arr[i];
if (maxRightSubsequenceSum > maxRight){
maxRight = maxRightSubsequenceSum;
iright = i;
}
}
return Math.max(Math.max(maxLeftSum,maxLeft+maxRight),Math.max(maxRightSum,maxLeft+maxRight));
}
}
}
运行结果:
[5,8]21
Process finished with exit code 0