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: 1
💡 Note: Valid subarrays: [-1]=-1, [2]=2 ✓, [-3]=-3, [-1,2]=1 ✓, [2,-3]=-1. Minimum positive sum 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 INPUT Array nums: 2 i=0 -3 i=1 4 i=2 -1 i=3 2 i=4 Constraints: l = 2 (min length) r = 3 (max length) Find subarray where: - Length between l and r - Sum greater than 0 - Minimize the sum ALGORITHM STEPS 1 Initialize minSum = infinity 2 For each start index i Try all lengths l to r 3 Calculate sum If sum > 0, update min 4 Return result minSum or -1 if none Subarray Sums (len 2-3): [2,-3] = -1 (skip) [2,-3,4] = 3 (OK) [-3,4] = 1 (OK) [-3,4,-1] = 0 (skip) [4,-1] = 3 (OK) [4,-1,2] = 5 (OK) [-1,2] = 1 (OK) MIN! Min positive: 1 FINAL RESULT Optimal Subarray Found: -1 i=3 2 i=4 Length = 2 (valid: 2-3) OUTPUT 1 Verification: -1 + 2 = 1 Sum > 0: OK Min positive sum: OK Key Insight: Use sliding window or brute force to check all subarrays with length between l and r. Track minimum positive sum. Time: O(n*(r-l+1)), Space: O(1). For optimal, use prefix sums. TutorialsPoint - Minimum Positive Sum Subarray | Optimal Solution
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