3364. Minimum Positive Sum Subarray

LeetCode 力扣

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)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public:
    int minimumSumSubarray(const vector<int> &nums, int l, int r) {
        const int n = nums.size();
        int min_sum = numeric_limits<int>::max();
        int initial = 0;
        for (int i = 0; i < l - 1; ++i) {
            initial += nums[i];
        }

        for (int length = l; length <= r; ++length) {
            initial += nums[length - 1];
            int sum = initial;
            if (sum > 0 && sum < min_sum) {
                min_sum = sum;
            }

            for (int right = length; right < n; ++right) {
                sum += nums[right] - nums[right - length];
                if (sum > 0 && sum < min_sum) {
                    min_sum = sum;
                }
            }
        }

        return min_sum == numeric_limits<int>::max() ? -1 : min_sum;
    }
};
comments powered by Disqus