May LeetCoding Challenge15 之 Kadane's Algorithm

Posted yawenw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了May LeetCoding Challenge15 之 Kadane's Algorithm相关的知识,希望对你有一定的参考价值。

首先要了解什么是Kadane‘s 算法。

这个算法通常被用于在一个数组A中寻找到一个连续子数组最大和的值。

public int maxSubarraySumCircular(int[] A) {
        int N = A.length;

        int ans = A[0], cur = A[0];
        for (int i = 1; i < N; ++i) {
            cur = A[i] + Math.max(cur, 0);
            ans = Math.max(ans, cur);
        }

本题规定子数组可以呈循环式。

class Solution {
    public int maxSubarraySumCircular(int[] A) {
        int N = A.length;

        int ans = A[0], cur = A[0];
        for (int i = 1; i < N; ++i) {
            cur = A[i] + Math.max(cur, 0);
            ans = Math.max(ans, cur);
        }

        // ans is the answer for 1-interval subarrays.
        // Now, let‘s consider all 2-interval subarrays.
        // For each i, we want to know
        // the maximum of sum(A[j:]) with j >= i+2

        // rightsums[i] = A[i] + A[i+1] + ... + A[N-1]
        int[] rightsums = new int[N];
        rightsums[N-1] = A[N-1];
        for (int i = N-2; i >= 0; --i)
            rightsums[i] = rightsums[i+1] + A[i];

        // maxright[i] = max_{j >= i} rightsums[j]
        int[] maxright = new int[N];
        maxright[N-1] = A[N-1];
        for (int i = N-2; i >= 0; --i)
            maxright[i] = Math.max(maxright[i+1], rightsums[i]);

        int leftsum = 0;
        for (int i = 0; i < N-2; ++i) {
            leftsum += A[i];
            ans = Math.max(ans, leftsum + maxright[i+2]);
        }

        return ans;
    }
}

 

以上是关于May LeetCoding Challenge15 之 Kadane's Algorithm的主要内容,如果未能解决你的问题,请参考以下文章

May LeetCoding Challenge8 之 交叉相乘

May LeetCoding Challenge8 之 交叉相乘

May LeetCoding Challenge 之 标准二分查找法

May LeetCoding Challenge27 之 二分图

May LeetCoding Challenge27 之 二分图

May LeetCoding Challenge19 之 单调栈2.0