#918
Medium Algorithms Maximum sum circular subarray
Array Divide and Conquer Dynamic Programming Queue Monotonic Queue
49.5% acceptance
Feb 25, 2026
7287
342
Given a circular integer array nums of length n, return the maximum possible sum of a non-empty subarray of nums.
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].
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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn max_subarray_sum_circular(nums: Vec<i32>) -> i32 {
let total: i32 = nums.iter().sum();
let mut max_sum = nums[0]; let mut cur_max = 0;
let mut min_sum = nums[0]; let mut cur_min = 0;
for &x in &nums {
cur_max = (cur_max + x).max(x); max_sum = max_sum.max(cur_max);
cur_min = (cur_min + x).min(x); min_sum = min_sum.min(cur_min);
}
if max_sum < 0 { max_sum } else { max_sum.max(total - min_sum) }
}
}