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
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ยฒ)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code