Minimum Positive Sum Subarray - Problem

You're given an integer array nums and two integers l and r. Your task is to find the minimum positive sum among all contiguous subarrays whose length is between l and r (inclusive).

A subarray is a contiguous sequence of elements within the array. You need to consider all possible subarrays with lengths from l to r, calculate their sums, and return the smallest sum that is greater than 0.

If no such subarray exists (i.e., all valid subarrays have sums โ‰ค 0), return -1.

Example: For array [2, -1, 3, -4, 5] with l=2, r=3, we check subarrays of length 2 and 3. The subarray [2, -1] has sum 1, which might be our answer if it's the minimum positive sum found.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [3, -2, 1, 4], l = 2, r = 3
โ€บ Output: 1
๐Ÿ’ก Note: Valid subarrays: [3,-2] (sum=1), [-2,1] (sum=-1), [1,4] (sum=5), [3,-2,1] (sum=2), [-2,1,4] (sum=3). The minimum positive sum is 1.
example_2.py โ€” No Positive Sum
$ Input: nums = [-1, -2, -3, -4], l = 2, r = 4
โ€บ Output: -1
๐Ÿ’ก Note: All possible subarrays have negative sums, so we return -1.
example_3.py โ€” Single Element
$ Input: nums = [1], l = 1, r = 1
โ€บ Output: 1
๐Ÿ’ก Note: Only one valid subarray [1] with sum 1, which is positive.

Constraints

  • 1 โ‰ค nums.length โ‰ค 100
  • 1 โ‰ค l โ‰ค r โ‰ค nums.length
  • -1000 โ‰ค nums[i] โ‰ค 1000

Visualization

Tap to expand
๐Ÿ›’ Shopping Budget ChallengeStore Items (Prices/Discounts):$3-$2$1$4Must buy 2-3 consecutive items (l=2, r=3)Cart 1: $1Cart 2: -$1Cart 3: $5๐ŸŽฏ Minimum Positive Cost: $1Found by checking all valid cart combinations
Understanding the Visualization
1
Scan the Store
Look at all possible starting positions in the store aisle
2
Try Different Cart Sizes
For each start position, try cart sizes from l to r items
3
Calculate Total Cost
Sum up costs (positive prices, negative discounts) for each combination
4
Track Minimum Spend
Keep track of the smallest positive total cost found
Key Takeaway
๐ŸŽฏ Key Insight: Use prefix sums to avoid recalculating subarray sums, turning an O(nยณ) problem into O(nยฒ)
Asked in
Google 23 Amazon 18 Microsoft 15 Meta 12
24.5K Views
Medium Frequency
~15 min Avg. Time
892 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