最大子序列和问题的求解。

8 篇文章 0 订阅
  1. 非递归
    时间复杂度为:O(N)
/* 最大子序列和问题的求解。
 */
class Test {
    public static void main(String[] args) {
        int a[] = { 1, 2, -1, 2, -4, -10, 7, -1, -9, 4, 2, -3, 5, -9 };
        System.out.println(maxSubSum4(a));
    }

    public static int maxSubSum4(int[] a) {
        int maxSum = 0, thisSum = 0;
        for (int i = 0; i < a.length; i++) {
            thisSum += a[i];
            if (thisSum > maxSum)
                maxSum = thisSum;
            else if (thisSum < 0)
                thisSum = 0;
        }
        return maxSum;
    }
}
  1. 递归,“分治”策略
    时间复杂度为:O(NlogN)
/* 最大子序列和问题的求解。
 */
class Test {
    public static void main(String[] args) {
        int a[] = { 1, 2, -1, 2, -4, -10, 7, -1, -9, 4, 2, -3, 5, -9 };
        System.out.println(maxSubSum3(a));
    }

    public static int maxSubSum3(int[] a) {
        return maxSumRec(a, 0, a.length - 1);
    }

    public static int maxSumRec(int[] a, int left, int right) {
        // 基准情形
        if (left == right)
            if (a[left] > 0)
                return a[left];
            else
                return 0;
        int center = (left + right) / 2;
        // 左边和右边最大值,递归求解
        int maxLeftSum = maxSumRec(a, left, center);
        int maxRightSum = maxSumRec(a, center + 1, right);
        // 累加求左边界和
        int maxLeftBorderSum = 0, leftBorderSum = 0;
        for (int i = center; i >= left; i--) {
            leftBorderSum += a[i];
            if (leftBorderSum > maxLeftBorderSum)
                maxLeftBorderSum = leftBorderSum;
        }
        // 累加求右边界和
        int maxRightBorderSum = 0, rightBorderSum = 0;
        for (int i = center + 1; i <= right; i++) {
            rightBorderSum += a[i];
            if (rightBorderSum > maxRightBorderSum)
                maxRightBorderSum = rightBorderSum;
        }
        return max3(maxLeftSum, maxRightSum, maxLeftBorderSum + maxRightBorderSum);
    }

    public static int max3(int a, int b, int c) {
        int max = a > b ? a : b;
        max = max > c ? max : c;
        return max;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值