Intuition
Try every allowed window size; for each, slide a fixed-width window across the array updating its sum in O(1) per step, and keep the smallest sum that stays above zero.
Explanation
Idea
We need the smallest positive sum among all contiguous subarrays whose length falls in [l, r]. Because the length is restricted, we can look at each allowed length separately. For one fixed length k, a fixed-size sliding window lets us compute every window's sum in O(1): when the window moves one step right, add the element that entered and subtract the one that left. Across all lengths l..r we track the minimum sum that is strictly greater than 0.
Walk-through on nums = [3, -2, 1, 4], l = 2, r = 3
Allowed lengths are 2 and 3.
Length 2. Slide a width-2 window:
[3, -2]→ sum1. It is positive, sobest = 1.- Slide right: drop
3, add1→[-2, 1]sum-1. Not positive, ignore. - Slide right: drop
-2, add4→[1, 4]sum5. Positive but5 > 1, sobeststays1.
Length 3. Slide a width-3 window:
[3, -2, 1]→ sum2. Positive but2 > 1,beststays1.- Slide right: drop
3, add4→[-2, 1, 4]sum3. Positive but3 > 1,beststays1.
No window beat 1, so the answer is 1.
If no window of any allowed length ever has a positive sum, best is never set and we return -1 (as in nums = [-2, 2, -3, 1], l = 2, r = 3).
Why the sliding update is correct
For a fixed width k, the window at position i covers nums[i..i+k-1]. Moving to i+1 removes nums[i] and adds nums[i+k], so sum_{i+1} = sum_i - nums[i] + nums[i+k]. Each window sum therefore costs O(1) after the first.
Complexity
- Time: O(n · (r − l + 1)), which is at most O(n²). For each of the
r − l + 1lengths we make a single linear pass. - Space: O(1). Only a running sum and the best answer are kept.
Implementation
class Solution {
public int minimumSumSubarray(int[] nums, int l, int r) {
int n = nums.length;
long best = Long.MAX_VALUE;
for (int size = l; size <= r; size++) {
long window = 0;
for (int i = 0; i < size; i++) window += nums[i];
if (window > 0) best = Math.min(best, window);
for (int i = size; i < n; i++) {
window += nums[i] - nums[i - size];
if (window > 0) best = Math.min(best, window);
}
}
return best == Long.MAX_VALUE ? -1 : (int) best;
}
}