public class FindMaxChildArray {
public static void main(String[] args) {
//int[] arr = new int[]{5,-4,2,3,7,-1, -4, 3, 6,-8,6};
int[] arr = new int[]{-5,-4,2,3,7,-1, -4, 3, 6,-8,6};
//int[] arr = new int[]{-5,-4,-2,-3,-7,-1, -4, -3, -6,-8,-6};
//int[] arr = new int[]{5,4,2,3,7,1, 4, 3, 6,8,6};
int[] result = find(arr, 0, arr.length-1);
System.out.println("From index " + result[1] + " To " + result[2] + " is max,and the SUM is "+result[0]+".");
}
public static int[] find(int[] arr, int from, int to) {
if(from == to) {
return new int[]{arr[from], from, to};
}
int mid = (from + to) / 2;
int[] maxLeft = find(arr, from, mid);
int[] maxRight = find(arr, mid + 1, to);
int[] maxMid = findThrough(arr, from, mid, to);
int max;
if(maxLeft[0] > maxRight[0]) {
max = maxLeft[0];
} else {
max = maxRight[0];
}
if(max < maxMid[0]) {
return maxMid;
} else if(max == maxLeft[0]){
return maxLeft;
} else {
return maxRight;
}
}
public static int[] findThrough(int[] arr, int from, int mid, int to ) {
int maxLeft = 0;
int maxRight = 0;
int leftIndex = mid;
int rightIndex = mid;
int sum = 0;
for(int i=mid-1; i>=from; i--) {
sum += arr[i];
if(sum > maxLeft) {
maxLeft = sum;
leftIndex = i;
}
}
sum = 0;
for(int i=mid+1; i<=to; i++) {
sum += arr[i];
if(sum > maxRight) {
maxRight = sum;
rightIndex = i;
}
}
return new int[]{maxLeft+maxRight+arr[mid], leftIndex, rightIndex};
}
}
结果:From index 2 To 8 is max,and the SUM is 16.
求数组中的一个子数组,其和是最大的
最新推荐文章于 2021-02-09 11:31:16 发布