# 4.1 最大子数组问题(分治法)

public class MaxSubArray {
//暴力求解
int maxSubArray1(int arr[]) {
int max = 0;
for (int i = 0; i < arr.length; i++) {
int curMax = arr[i];
for (int j = i + 1; j < arr.length; j++) {
curMax = arr[j] + curMax;
if (curMax > max) {
max = curMax;
}
}
}
return max;
}

//动态规划
int maxSubArray2(int arr[]) {
int max = arr[0];
int tempMax = max;
for (int i = 1; i < arr.length; i++) {
tempMax = Math.max(tempMax + arr[i], arr[i]);
if (tempMax >= max) {
max = tempMax;
}
}
return max;
}

//分治法
int findMaxSubArray(int arr[], int left, int middle, int right) {
int leftSum = 0;
int leftMax = 0;
int rightSum = 0;
int rightMax = 0;
//找出左边的最大值
for (int i = left; i < middle; i++) {
leftSum = leftSum + arr[i]>arr[i]?leftSum + arr[i]:arr[i];
if (leftSum > leftMax) {
leftMax = leftSum;
}
}

//找出右边的最大值
for (int i = middle; i <= right; i++) {
rightSum = rightSum + arr[i]>arr[i]?rightSum + arr[i]:arr[i];
if (rightSum > rightMax) {
rightMax = rightSum;
}
}
return Math.max(leftMax, rightMax);
}

//划分
int maxSubArrayDevide(int arr[],int left,int right) {
if (left == right){
return arr[left];
}
int middle = (left+right)/2;
maxSubArrayDevide(arr,left,middle);
maxSubArrayDevide(arr,middle+1,right);
return  findMaxSubArray(arr,left,middle+1,right);
}

//统一调用
int maxSubArray3(int arr[]){
return  maxSubArrayDevide(arr,0,arr.length - 1);
}

//test
public static void main(String[] args) {
int i = new MaxSubArray().maxSubArray3(new int[]{2, 1, 4, -1, 0, -2});
System.out.println("result = " + i);
}

}

05-31
03-16 390

06-30 7955
10-14 127
10-14 264
01-30 79