1. Description
Given an integer array nums and two integers l and r, find the smallest positive sum among all contiguous subarrays with lengths from l through r, inclusive.
Return that sum, or -1 if no qualifying subarray exists.
2. Example
Example 1
Input: nums = [3,-2,1,4], l = 2, r = 3
Output: 1
Explanation: The eligible positive sums are 1 for [3,-2], 5 for [1,4], 2 for [3,-2,1], and 3 for [-2,1,4]. The smallest is 1.
Example 2
Input: nums = [-2,2,-3,1], l = 2, r = 3
Output: -1
Explanation: Every subarray of length 2 or 3 has a nonpositive sum.
Example 3
Input: nums = [1,2,3,4], l = 2, r = 4
Output: 3
Explanation: [1,2] has length 2 and gives the smallest positive sum, 3.
3. Constraints
- 1 <= nums.length <= 100
- 1 <= l <= r <= nums.length
- -1000 <= nums[i] <= 1000
4. Solutions
Sliding Window
n = nums.size()
Time complexity: O(n * (r - l + 1))
Space complexity: O(1)
| |