java求最大子数组 (分治算法)

当一个数组有负数时,最大子数组才会有意义。

package shu.quan.demo;

/**
 * 求最大子串的值,并求出脚标。
 */
public class MaxSubsequence {
    static int ileft = 0, iright = 0;
    public static void main(String[] args){
        int[] arr = new int[]{1,5,-5,6,-13,4,8,-5,14};
        int res = maxSubsequence(arr);
        System.out.print("["+ileft+","+iright+"]"+res);

    }

    static int maxSubsequence(int[] arr){
        return maxSubsequence(arr,0,arr.length - 1);
    }

    static int maxSubsequence(int[] arr, int left, int right){
        if(left == right){
            return arr[left];
        }else {
            int center = (left + right) /2;

            int maxLeftSum = maxSubsequence(arr, left, center);
            int maxRightSum = maxSubsequence(arr, center + 1, right);
            int maxLeftSubsequenceSum = 0, maxLeft = 0;
            for (int i = center; i >= left; i--) {
                maxLeftSubsequenceSum += arr[i];
                if (maxLeftSubsequenceSum > maxLeft){
                    maxLeft = maxLeftSubsequenceSum;
                    ileft = i;
                }

            }

            int maxRightSubsequenceSum = 0, maxRight = 0;
            for (int i = center + 1; i <= right; i++) {
                maxRightSubsequenceSum += arr[i];
                if (maxRightSubsequenceSum > maxRight){
                    maxRight = maxRightSubsequenceSum;
                    iright = i;
                }

            }

            return Math.max(Math.max(maxLeftSum,maxLeft+maxRight),Math.max(maxRightSum,maxLeft+maxRight));

        }
    }
}

运行结果:

[5,8]21
Process finished with exit code 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值