918. Maximum Sum Circular Subarray

https://leetcode.com/problems/maximum-sum-circular-subarray/

Given a circular array C of integers represented by A, find the maximum possible sum of a non-empty subarray of C.

Here, a circular array means the end of the array connects to the beginning of the array. (Formally, C[i] = A[i] when 0 <= i < A.length, and C[i+A.length] = C[i] when i >= 0.)

Also, a subarray may only include each element of the fixed buffer A at most once. (Formally, for a subarray C[i], C[i+1], ..., C[j], there does not exist i <= k1, k2 <= j with k1 % A.length = k2 % A.length.)

Example 1:

Input: [1,-2,3,-2]
Output: 3
Explanation: Subarray [3] has maximum sum 3

Example 2:

Input: [5,-3,5]
Output: 10
Explanation: Subarray [5,5] has maximum sum 5 + 5 = 10

Example 3:

Input: [3,-1,2,-1]
Output: 4
Explanation: Subarray [2,-1,3] has maximum sum 2 + (-1) + 3 = 4

Example 4:

Input: [3,-2,2,-3]
Output: 3
Explanation: Subarray [3] and [3,-2,2] both have maximum sum 3

Example 5:

Input: [-2,-3,-1]
Output: -1
Explanation: Subarray [-1] has maximum sum -1

Note:

  1. -30000 <= A[i] <= 30000

  2. 1 <= A.length <= 30000

Thoughts

给定数组看作首尾相连的循环数组,问循环数组内最大子数组和是多少。

  1. 如果不是环,subarray sum标准解法就是遍历每个元素算出当前sum, 拿它减去之前的min_sum得出的sum就是max_sum候选, 遍历时不断更新max_sum候选,最后剩下的就是最大的。

  2. 成环后最直接的想法就是把它看成原数组x2. 这时max_sum可能是如图二中那样拼接而成。这时我们与其找max_sum, 不如找无环情况下的min_sum, 最后max_sum = total_sum - min_sum。找min_sum的流程和找max_sum是一致的。

  3. 最后比较无环时的max_sum和有环时total - min_sum哪个大。 但如果全是负的时候,min_sum会变成整个数组,导致total - min_sum = 0, 因此全是负的时候,应当选最小的那个负数,即无环时的max_sum。

Code

class Solution:
    def maxSubarraySumCircular(self, A: List[int]) -> int:
        N = len(A)
        dp_mx, dp_mi, s = [-math.inf] * (N + 1), [math.inf] * (N + 1), 0
        for i, a in enumerate(A):
            s += a
            dp_mx[i + 1] = max(dp_mx[i], 0) + a
            dp_mi[i + 1] = min(dp_mi[i], 0) + a
        if dp_mi[-1] == s: return max(dp_mx[1:])
        return max(max(dp_mx[1:]), s - min(dp_mi[1:]) )
        
class Solution {
public:
    int maxSubarraySumCircular(vector<int>& A) {
        int max_res = INT_MIN, min_sum = 0, sum = 0;
        for (int a : A) {
            sum += a;
            max_res = max(max_res, sum - min_sum);
            min_sum = min(min_sum, sum);
        }

        int min_res = INT_MAX, max_sum = 0;
        sum = 0;
        for (int a : A) {
            sum += a;
            min_res = min(min_res, sum - max_sum);
            max_sum = max(max_sum, sum);
        }
        if (min_res == sum) return max_res;

        return max(max_res, sum - min_res);
    }
};

Analysis

时间复杂度O(N)

Last updated