|
| 1 | +# 918. Maximum Sum Circular Subarray |
| 2 | +Given a **circular integer array** `nums` of length `n`, return *the maximum possible sum of a non-empty **subarray** of* `nums`. |
| 3 | + |
| 4 | +A **circular array** means the end of the array connects to the beginning of the array. Formally, the next element of `nums[i]` is `nums[(i + 1) % n]` and the previous element of `nums[i]` is `nums[(i - 1 + n) % n]`. |
| 5 | + |
| 6 | +A **subarray** may only include each element of the fixed buffer `nums` at most once. Formally, for a subarray `nums[i], nums[i + 1], ..., nums[j]`, there does not exist `i <= k1`, `k2 <= j` with `k1 % n == k2 % n`. |
| 7 | + |
| 8 | +#### Example 1: |
| 9 | +<pre> |
| 10 | +<strong>Input:</strong> nums = [1,-2,3,-2] |
| 11 | +<strong>Output:</strong> 3 |
| 12 | +<strong>Explanation:</strong> Subarray [3] has maximum sum 3. |
| 13 | +</pre> |
| 14 | + |
| 15 | +#### Example 2: |
| 16 | +<pre> |
| 17 | +<strong>Input:</strong> nums = [5,-3,5] |
| 18 | +<strong>Output:</strong> 10 |
| 19 | +<strong>Explanation:</strong> Subarray [5,5] has maximum sum 5 + 5 = 10. |
| 20 | +</pre> |
| 21 | + |
| 22 | +#### Example 3: |
| 23 | +<pre> |
| 24 | +<strong>Input:</strong> nums = [-3,-2,-3] |
| 25 | +<strong>Output:</strong> -2 |
| 26 | +<strong>Explanation:</strong> Subarray [-2] has maximum sum -2. |
| 27 | +</pre> |
| 28 | + |
| 29 | +#### Constraints: |
| 30 | +* `n == nums.length` |
| 31 | +* <code>1 <= n <= 3 * 10<sup>4</sup></code> |
| 32 | +* <code>-3 * 10<sup>4</sup> <= nums[i] <= 3 * 10<sup>4</sup></code> |
| 33 | + |
| 34 | +## Solutions (Rust) |
| 35 | + |
| 36 | +### 1. Solution |
| 37 | +```Rust |
| 38 | +impl Solution { |
| 39 | + pub fn max_subarray_sum_circular(nums: Vec<i32>) -> i32 { |
| 40 | + let sum = nums.iter().sum(); |
| 41 | + let mut max_sum = nums[0]; |
| 42 | + let mut min_sum = nums[0]; |
| 43 | + let mut prefix_sum = nums[0]; |
| 44 | + let mut ret = nums[0].max(sum); |
| 45 | + |
| 46 | + for i in 1..nums.len() { |
| 47 | + prefix_sum += nums[i]; |
| 48 | + ret = ret |
| 49 | + .max(prefix_sum - min_sum) |
| 50 | + .max(sum - prefix_sum + max_sum); |
| 51 | + max_sum = max_sum.max(prefix_sum); |
| 52 | + min_sum = min_sum.min(prefix_sum); |
| 53 | + } |
| 54 | + |
| 55 | + ret |
| 56 | + } |
| 57 | +} |
| 58 | +``` |
0 commit comments