public class FindMaximumSubarray {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] A = {3,-1,-2,3,6,-2,25,-3};
SubscriptSum findMaxSubbary = findMaxSubbary(A, 0, A.length - 1);
SubscriptSum findMaxSubbary1 = findMaxS(A, 0, A.length - 1);
SubscriptSum findMaxSline = findMaxSline(A);
System.out.println(findMaxSubbary.left + " " + findMaxSubbary.right + " " + findMaxSubbary.sum);
System.out.println(findMaxSubbary1.left + " " + findMaxSubbary1.right + " " + findMaxSubbary1.sum);
System.out.println(findMaxSline.left + " " + findMaxSline.right + " " + findMaxSline.sum);
}
//
public static SubscriptSum findMaxSubbary(int[] A, int low, int high) {
if(high == low ) {
return new SubscriptSum(low, high, A[low]);
}else {
int mid = (high + low) / 2;
SubscriptSum l = findMaxSubbary(A, low, mid);
SubscriptSum r = findMaxSubbary(A, mid + 1, high);
SubscriptSum m = findMaxCrossingSubbary(A, low, mid, high);
if(l.sum >= r.sum && l.sum >= m.sum) {
return l;
}else if(r.sum >= l.sum && r.sum >= m.sum) {
return r;
}else {
return m;
}
}
}
public static SubscriptSum findMaxCrossingSubbary(int[] A, int low, int mid, int high) {
int leftSum = 0;
int rightSum = 0;
int maxleftScrip = Integer.MIN_VALUE;
int maxRightScrip = Integer.MAX_VALUE;
int sum = 0;
for(int i = mid; i >= low; i--) {
sum = sum + A[i];
if(sum > leftSum) {
leftSum = sum;
maxleftScrip = i;
}
}
sum = 0;
for(int i = mid+1; i <= high; i++) {
sum = sum + A[i];
if(sum > rightSum) {
rightSum = sum;
maxRightScrip = i;
}
}
return new SubscriptSum(maxleftScrip, maxRightScrip, leftSum + rightSum);
}
//暴力法
public static SubscriptSum findMaxS(int[] A, int low, int high) {
int sum = 0;
int Max = 0;
int left = Integer.MIN_VALUE;
int right = Integer.MAX_VALUE;
Max = A[0];
left = 0;
right = 0;
for(int i = 0; i < A.length; i++) {
sum = A[i];
if(sum > Max) {
Max = sum;
left = i;
right = i;
}
for(int j = i +1; j < A.length; j++) {
sum += A[j];
if(sum >= Max) {
Max = sum;
left = i;
right =j;
}
}
}
return new SubscriptSum(left, right, Max);
}
//线性法
public static SubscriptSum findMaxSline(int[] A) {
int max = 0;
int left = 0;
int right = 0;
int passibleMax = 0;
int passibleLeft = 0;
int passibleRight = 0;
boolean newSubArray = true;
for(int i = 0; i < A.length; i++) {
if(newSubArray) {
if(A[i] > 0) {
passibleLeft = i;
passibleRight = i;
newSubArray = false;
}
}
if(!newSubArray) {
passibleMax += A[i];
if(passibleMax > max) {
max = passibleMax;
left = passibleLeft;
right = i;
}
if(passibleMax <= 0) {
newSubArray = true;
passibleMax = 0;
}
}
}
return new SubscriptSum(left, right, max);
}
}
class SubscriptSum{
public int left;
public int right;
public int sum;
public SubscriptSum(int left, int right, int sum) {
this.left = left;
this.right = right;
this.sum = sum;
}
}