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:
Example 2:
Example 3:
Example 4:
Example 5:
Note:
-30000 <= A[i] <= 30000
1 <= A.length <= 30000
Thoughts
给定数组看作首尾相连的循环数组,问循环数组内最大子数组和是多少。
如果不是环,subarray sum标准解法就是遍历每个元素算出当前sum, 拿它减去之前的min_sum得出的sum就是max_sum候选, 遍历时不断更新max_sum候选,最后剩下的就是最大的。
成环后最直接的想法就是把它看成原数组x2. 这时max_sum可能是如图二中那样拼接而成。这时我们与其找max_sum, 不如找无环情况下的min_sum, 最后max_sum = total_sum - min_sum。找min_sum的流程和找max_sum是一致的。
最后比较无环时的max_sum和有环时total - min_sum哪个大。 但如果全是负的时候,min_sum会变成整个数组,导致total - min_sum = 0, 因此全是负的时候,应当选最小的那个负数,即无环时的max_sum。
Code
Analysis
时间复杂度O(N)
Last updated
Was this helpful?