3364. Minimum Positive Sum Subarray
Problem Description
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.
Intuition
To solve this problem, the goal is to find a subarray within the array nums
that satisfies two conditions: its length is between l
and r
, and its sum is greater than zero. Among all possible subarrays that meet these criteria, we want to find the one with the smallest sum.
The approach involves checking each possible starting point i
of a subarray, and for each starting point, incrementally extending the subarray to include more elements, one at a time, until the end of the array is reached. By maintaining a running sum for the subarray, we can efficiently compute the sum of any subarray defined by a starting point i
and an ending point j
.
For each subarray from i
to j
, we need to verify if its length is within the bounds l
and r
and if its sum is positive. If these conditions are satisfied, we compare its sum with the current minimum sum found so far and update the minimum if the current sum is smaller.
Finally, if no subarray meeting the conditions is found, we return -1
. Otherwise, we return the minimum sum found.
Learn more about Prefix Sum and Sliding Window patterns.
Solution Approach
The solution employs a brute-force enumeration strategy to explore all possible subarrays of nums
that could be the answer. Here's a detailed breakdown of the approach:
-
Initialization:
- Begin by setting a variable
ans
toinf
, representing the smallest sum found for subarrays that meet the criteria. Ifans
remainsinf
, it implies no suitable subarray was found.
- Begin by setting a variable
-
Enumeration of Subarrays:
- Iterate over each possible starting index
i
of the subarray. For eachi
, initialize a sums
to zero. - From this starting index
i
, iterate through the subsequent elements to create the subarray ending at indexj
. - Maintain a running sum
s
that adds each elementnums[j]
from indexi
toj
.
- Iterate over each possible starting index
-
Verification and Update:
- For each subarray from
i
toj
, check whether its length falls within the bounds[l, r]
using the conditionl <= j - i + 1 <= r
. - Check if the subarray sum
s
is greater than zero. If both conditions are true, updateans
to be the minimum of the currentans
and the sums
.
- For each subarray from
-
Result Determination:
- After all subarrays have been considered, return
-1
if no valid subarray has been found (i.e.,ans
is stillinf
). Otherwise, returnans
.
- After all subarrays have been considered, return
This approach is simple and direct, involving the use of nested loops to evaluate all possible subarrays, while leveraging a simple mathematical check to ensure the subarray meets the given conditions.
Ready to land your dream job?
Unlock your dream job with a 2-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Consider an example where nums = [4, -1, 2, 1, -5, 6]
, l = 1
, and r = 3
.
Step-by-step Walkthrough:
-
Initialization:
- Set
ans
toinf
to record the minimum sum found for subarrays meeting the criteria.
- Set
-
Enumeration of Subarrays:
-
Start with
i = 0
, initializes = 0
.-
For
j = 0
: Addnums[0] = 4
tos
. Sos = 4
.- Subarray:
[4]
with length1
. Since1 <= 1 <= 3
and sum is positive, updateans = 4
.
- Subarray:
-
For
j = 1
: Addnums[1] = -1
tos
. Sos = 3
.- Subarray:
[4, -1]
with length2
. Since1 <= 2 <= 3
and sum is positive, updateans = 3
.
- Subarray:
-
For
j = 2
: Addnums[2] = 2
tos
. Sos = 5
.- Subarray:
[4, -1, 2]
with length3
. Since1 <= 3 <= 3
and sum is positive,ans
remains3
.
- Subarray:
-
-
Starting with
i = 1
, initializes = 0
.-
For
j = 1
: Addnums[1] = -1
tos
. Sos = -1
.- Subarray:
[-1]
with length1
. Sum is not positive,ans
remains3
.
- Subarray:
-
For
j = 2
: Addnums[2] = 2
tos
. Sos = 1
.- Subarray:
[-1, 2]
with length2
. Since1 <= 2 <= 3
and sum is positive, updateans = 1
.
- Subarray:
-
For
j = 3
: Addnums[3] = 1
tos
. Sos = 2
.- Subarray:
[-1, 2, 1]
with length3
. Since1 <= 3 <= 3
and sum is positive,ans
remains1
.
- Subarray:
-
-
Starting with
i = 2
, initializes = 0
.-
For
j = 2
: Addnums[2] = 2
tos
. Sos = 2
.- Subarray:
[2]
with length1
. Since1 <= 1 <= 3
and sum is positive,ans
remains1
.
- Subarray:
-
For
j = 3
: Addnums[3] = 1
tos
. Sos = 3
.- Subarray:
[2, 1]
with length2
. Sum is positive butans
remains1
.
- Subarray:
-
For
j = 4
: Addnums[4] = -5
tos
. Sos = -2
.- Subarray:
[2, 1, -5]
with length3
. Sum is not positive,ans
remains1
.
- Subarray:
-
-
Continue evaluating subarrays starting at
i = 3
,i = 4
, andi = 5
similar to above logic, but none will yield a smaller positive sum than1
.
-
-
Result Determination:
- After evaluating all possible subarrays, the smallest positive sum found is
1
. Thus, return1
as the minimum sum of a subarray meeting the conditions.
- After evaluating all possible subarrays, the smallest positive sum found is
This process rigorously checks each potential candidate, ensuring the smallest possible subarray sum is identified.
Solution Implementation
1from typing import List
2from math import inf
3
4class Solution:
5 def minimumSumSubarray(self, nums: List[int], l: int, r: int) -> int:
6 n = len(nums) # Get the length of the input list
7 ans = inf # Initialize the answer to infinity
8
9 # Iterate over each starting point of the subarray
10 for i in range(n):
11 s = 0 # Initialize the current subarray sum to 0
12
13 # Iterate over each ending point of the subarray starting from i
14 for j in range(i, n):
15 s += nums[j] # Add the current element to the subarray sum
16
17 # Check if the current subarray length is within the given range [l, r]
18 # and whether the sum is greater than 0
19 if l <= (j - i + 1) <= r and s > 0:
20 ans = min(ans, s) # Update the minimum positive subarray sum
21
22 # Return -1 if no valid subarray sum was found, otherwise return the minimum sum
23 return -1 if ans == inf else ans
24
1import java.util.List;
2
3class Solution {
4 public int minimumSumSubarray(List<Integer> nums, int l, int r) {
5 int n = nums.size(); // Get the size of the list
6 final int INF = Integer.MAX_VALUE; // Define a constant for infinity
7 int minSum = INF; // Initialize the minimum sum as infinity
8
9 // Iterate over each starting point of the subarray
10 for (int i = 0; i < n; ++i) {
11 int currentSum = 0; // Initialize the current sum of the subarray
12
13 // Iterate over each ending point of the subarray
14 for (int j = i; j < n; ++j) {
15 currentSum += nums.get(j); // Add the current element to the sum
16 int k = j - i + 1; // Calculate the length of the current subarray
17
18 // Check if the subarray length is within the specified range and has a positive sum
19 if (k >= l && k <= r && currentSum > 0) {
20 minSum = Math.min(minSum, currentSum); // Update the minimum sum if a smaller positive sum is found
21 }
22 }
23 }
24
25 // If no valid subarray is found, return -1; otherwise, return the minimum sum found
26 return minSum == INF ? -1 : minSum;
27 }
28}
29
1#include <vector>
2#include <algorithm>
3#include <climits>
4
5class Solution {
6public:
7 int minimumSumSubarray(std::vector<int>& nums, int l, int r) {
8 int n = nums.size();
9 const int INF = INT_MAX; // Define infinity as the maximum integer value
10 int answer = INF; // Initialize answer with infinity
11
12 // Iterate over each starting point of the subarray
13 for (int start = 0; start < n; ++start) {
14 int currentSum = 0; // Initialize the current sum of the subarray
15
16 // Iterate to find subarrays starting from 'start' index
17 for (int end = start; end < n; ++end) {
18 currentSum += nums[end]; // Add the current element to the subarray sum
19 int length = end - start + 1; // Calculate the length of the current subarray
20
21 // Check if the subarray length is within bounds and the sum is positive
22 if (length >= l && length <= r && currentSum > 0) {
23 answer = std::min(answer, currentSum); // Update the answer with the minimum positive subarray sum
24 }
25 }
26 }
27
28 // If the answer is still infinity, return -1, otherwise return the minimum sum found
29 return answer == INF ? -1 : answer;
30 }
31};
32
1// This function finds the minimum sum of any continuous subarray in `nums`
2// with a length between `l` and `r`, inclusive. If all sums are non-positive,
3// it returns -1.
4function minimumSumSubarray(nums: number[], l: number, r: number): number {
5 const n = nums.length; // Determine the length of the input array
6 let ans = Infinity; // Initialize the minimum sum to infinity
7
8 // Iterate over each starting point of the subarray
9 for (let i = 0; i < n; ++i) {
10 let currentSum = 0; // Initialize the current sum to 0
11
12 // Iterate over each ending point of the subarray starting from i
13 for (let j = i; j < n; ++j) {
14 currentSum += nums[j]; // Add the current element to the current sum
15 const currentLength = j - i + 1; // Calculate the current subarray length
16
17 // Check if the current subarray meets the length condition
18 // and if the sum is positive
19 if (currentLength >= l && currentLength <= r && currentSum > 0) {
20 ans = Math.min(ans, currentSum); // Update the minimum sum if needed
21 }
22 }
23 }
24
25 // If no valid subarray was found (ans remained infinity), return -1
26 return ans === Infinity ? -1 : ans;
27}
28
Time and Space Complexity
The time complexity of the given code is O(n^2)
, where n
is the length of the array nums
. This is because there are two nested loops: the outer loop iterates over each starting point of the subarray in O(n)
time, and the inner loop iterates over each ending point for that starting point, also in O(n)
time. Therefore, the overall complexity is O(n * n)
.
The space complexity is O(1)
because the algorithm uses a constant amount of additional space regardless of the input size. The variables n
, ans
, i
, s
, and j
are used, which have a space complexity that does not depend on n
.
Learn more about how to find time and space complexity quickly.
Is the following code DFS or BFS?
void search(Node root) { if (!root) return; visit(root); root.visited = true; for (Node node in root.adjacent) { if (!node.visited) { search(node); } } }
Recommended Readings
Prefix Sum The prefix sum is an incredibly powerful and straightforward technique Its primary goal is to allow for constant time range sum queries on an array What is Prefix Sum The prefix sum of an array at index i is the sum of all numbers from index 0 to i By
https algomonster s3 us east 2 amazonaws com cover_photos stack svg Sliding Window Maximum Monotonic Stack We have an array and a sliding window defined by a start index and an end index The sliding window moves from left of the array to right There are always k elements in
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Want a Structured Path to Master System Design Too? Don’t Miss This!