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:

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

Analysis

时间复杂度O(N)

Last updated

Was this helpful?