Minimum Positive Sum Subarray - Problem

You are given an integer array nums and two integers l and r.

Your task is to find the minimum sum of a subarray whose size is between l and r (inclusive) and whose sum is greater than 0.

Return the minimum sum of such a subarray. If no such subarray exists, return -1.

A subarray is a contiguous non-empty sequence of elements within an array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,-3,4,-1,2], l = 2, r = 3
Output: 1
💡 Note: Check all subarrays of length 2-3: [2,-3]=-1 (negative), [-3,4]=1 ✓, [4,-1]=3 ✓, [-1,2]=1 ✓, [2,-3,4]=3 ✓, [-3,4,-1]=0 (not positive), [4,-1,2]=5 ✓. Minimum positive sum is 1.
Example 2 — All Negative
$ Input: nums = [-2,-3,-1], l = 2, r = 3
Output: -1
💡 Note: All possible subarrays have negative sums: [-2,-3]=-5, [-3,-1]=-4, [-1]=-1 (wrong length), [-2,-3,-1]=-6. No positive sum exists.
Example 3 — Single Positive Element
$ Input: nums = [-1,2,-3], l = 1, r = 2
Output: 2
💡 Note: Valid subarrays: [-1]=-1, [2]=2 ✓, [-3]=-3, [-1,2]=1 ✓, [2,-3]=-1. Minimum positive sum is 1, but wait - l=1,r=2 means length 1-2, so [2]=2 is length 1 which is valid. Minimum is 1 from [-1,2].

Constraints

  • 1 ≤ nums.length ≤ 105
  • -105 ≤ nums[i] ≤ 105
  • 1 ≤ l ≤ r ≤ nums.length

Visualization

Tap to expand
Minimum Positive Sum Subarray ProblemInput: nums = [2,-3,4,-1,2], l = 2, r = 32-34-12Valid subarrays (length 2-3):[2,-3] = -1 (negative)[-3,4] = 1 (positive) ✓[4,-1] = 3 (positive) ✓[-1,2] = 1 (positive) ✓[2,-3,4] = 3 (positive) ✓[-3,4,-1] = 0 (not positive)[4,-1,2] = 5 (positive) ✓Result: 1
Understanding the Visualization
1
Input
Array with positive/negative numbers, length constraints l,r
2
Process
Check all subarrays of length l to r, find positive sums
3
Output
Return minimum positive sum, or -1 if none exists
Key Takeaway
🎯 Key Insight: Use prefix sums to efficiently calculate all subarray sums and track the minimum positive value
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 6
23.4K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen