java实现:
public class 最大子数组问题 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int A[] = {13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7};
int[] r = Find_max_subarray(A, 0, A.length-1);
for(int i = r[0]; i<= r[1]; i++ ) {
System.out.print(A[i] + " ");
}
System.out.println("\n" + r[2]);
}
public static int[] Find_max_subarray(int A[], int low, int high) {
int result[] = new int[3];
if(low == high) {
result[0] = result[1] = low;
result[2] = A[low];
return result;
}
else {
int mid = (low+high)/2;
int[] leftsum = Find_max_subarray(A, low, mid);
int[] rightsum = Find_max_subarray(A, mid+1, high);
int[] cross_sum = Find_max_crossing_subarray(A, low, mid, high);
if(leftsum[2]>rightsum[2] && leftsum[2] > cross_sum[2]) {
return leftsum;
}
else if(rightsum[2] > leftsum[2] && rightsum[2] > cross_sum[2]) {
return rightsum;
}
else
return cross_sum;
}
}
public static int[]
Find_max_crossing_subarray(int A[], int low, int mid,int high) {
int left_sum = (int) -1e9;
int sum = 0;
int result[] = new int[3];
int max_left = 0 ;
int max_right = 0;
for(int i = mid; i>= low; i--) {
sum += A[i];
if(sum>left_sum) {
left_sum = sum;
max_left = i;
}
}
int right_sum = (int) -1e9;
sum = 0;
for(int i = mid+1; i < high; i++) {
sum += A[i];
if(sum>right_sum) {
right_sum = sum;
max_right = i;
}
}
result[0] = max_left;
result[1] = max_right;
result[2] = left_sum + right_sum;
return result;
}
}