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

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值