1. 程式人生 > >4.1 最大子陣列問題(分治法)

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); } }