LeetCode周賽#105 Q2 Maximum Sum Circular Subarray (最大連續子列和變形題)
題目來源:https://leetcode.com/contest/weekly-contest-105/problems/maximum-sum-circular-subarray/
問題描述
918. 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 arrayC[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
------------------------------------------------------------
題意
求迴圈陣列的最大連續子列和。與普通的最大連續子列和不同,這裡的陣列A是可以迴圈的,即從A[i]開始計算連續子列和,相當於計算數列B=A[i:end].append(A[0:i-1])的連續子列和。
------------------------------------------------------------
思路
傳統的最大連續子列和用動態規劃求解,dp[i]表示以i為結尾的最大連續子列和,複雜度為O(n)。如果直接將問題轉化為n個不同數列的最大連續子列和求最大,則複雜度為O(n^2),會超時。
解決方法比較有技巧性。迴圈陣列的最大連續子列和=max(非迴圈陣列的最大連續子列和,非迴圈陣列的總和-非迴圈陣列的最小連續子列和[但不能等於非迴圈陣列的總和本身]),注意約束條件“非迴圈陣列的最小連續子列和 不等於 非迴圈陣列的總和本身”是為了避免出現子列長度為0的情況。這樣原問題轉化為兩個複雜度為O(n)的子問題,總複雜度也是O(n).
------------------------------------------------------------
程式碼
class Solution {
public:
int dp[30005];
int maxSubArray(vector<int>& q)
{
int i, len = q.size(), vmax = -1000000000;
memset(dp, 0, sizeof(dp));
dp[0] = q[0];
for (i=1; i<len; i++)
{
if (dp[i-1] >= 0)
{
dp[i] = q[i] + dp[i-1];
}
else
{
dp[i] = q[i];
}
}
for (i=0; i<len; i++)
{
vmax = max(vmax, dp[i]);
}
return vmax;
}
int minSubArray(vector<int>& q)
{
int i, len = q.size(), vmin = 1000000000;
memset(dp, 0, sizeof(dp));
dp[0] = q[0];
for (i=1; i<len; i++)
{
if (dp[i-1] <= 0)
{
dp[i] = q[i] + dp[i-1];
}
else
{
dp[i] = q[i];
}
}
for (i=0; i<len; i++)
{
vmin = min(vmin, dp[i]);
}
return vmin;
}
int sumArray(vector<int>& q)
{
int i, len = q.size(), ans = 0;
for (i=0; i<len; i++)
{
ans += q[i];
}
return ans;
}
int maxSubarraySumCircular(vector<int>& A) {
int vmax = -1000000000, sum = sumArray(A), vmin = minSubArray(A);
vmax = max(vmax, maxSubArray(A));
if (sum != vmin)
{
vmax = max(vmax, sum - vmin);
}
return vmax;
}
};