[LeetCode] 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 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

环形子数组的最大和。这个题一开始读题的时候让我觉得是53题的followup,但是这个题用53题DP的思想好像还不太能套用得上去。这个题我参考了lee大神的帖子。基本思路是因为可以是环形的所以有可能最后最大的子数组有可能是如下几种情形,一种是直接在原数组的中间,一种是在原数组前半段截取一点出来,在后半段也截取一点出来。

对于第一种情况,其实就跟53题是一样的;但是对于第二种情况,如果我们需要得知断开的,最大的子数组,我们可以反过来去求连续的,最小的子数组的和,然后用整个数组的和 - 连续的,最小的子数组的和。唯一的corner case是如果整个数组都是由负数组成的,那么整个数组的和sum跟数组连续的,最小的子数组的和是一样的。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public int maxSubarraySumCircular(int[] A) {
 3         // corner case
 4         if (A == null || A.length == 0) {
 5             return 0;
 6         }
 7 
 8         // normal case
 9         int maxTillHere = A[0];
10         int max = A[0];
11         int minTillHere = A[0];
12         int min = A[0];
13         int sum = A[0];
14         for (int i = 1; i < A.length; i++) {
15             sum += A[i];
16             if (maxTillHere + A[i] > A[i]) {
17                 maxTillHere += A[i];
18             } else {
19                 maxTillHere = A[i];
20             }
21             max = Math.max(max, maxTillHere);
22 
23             if (minTillHere + A[i] < A[i]) {
24                 minTillHere += A[i];
25             } else {
26                 minTillHere = A[i];
27             }
28             min = Math.min(min, minTillHere);
29         }
30         if (sum == min) {
31             return max;
32         }
33         return Math.max(sum - min, max);
34     }
35 }

相关题目

53. Maximum Subarray

918. Maximum Sum Circular Subarray

LeetCode 题目总结

猜你喜欢

转载自www.cnblogs.com/cnoodle/p/12898615.html