#3364

Minimum Positive Sum Subarray

Easy
ArraySliding WindowPrefix Sum
LeetCode ↗

Approaches

💡

Intuition

Time O(n²)Space O(1)

The brute-force approach involves checking every possible subarray of lengths between l and r. This means calculating the sum for each subarray and keeping track of the smallest positive sum found.

⚙️

Algorithm

3 steps
  1. 1Step 1: Iterate through the array with a starting index.
  2. 2Step 2: For each starting index, iterate through possible ending indices to form subarrays of lengths from l to r.
  3. 3Step 3: Calculate the sum of each subarray and check if it's positive and smaller than the current minimum positive sum.
solution.py8 lines
1def min_positive_sum_subarray(nums, l, r):
2    min_sum = float('inf')
3    for i in range(len(nums)):
4        for j in range(i + l - 1, min(i + r, len(nums)) + 1):
5            subarray_sum = sum(nums[i:j])
6            if subarray_sum > 0:
7                min_sum = min(min_sum, subarray_sum)
8    return min_sum if min_sum != float('inf') else -1

Complexity note: The time complexity is O(n²) because we have two nested loops iterating through the array, and for each subarray, we calculate the sum which can take O(n) time in the worst case.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.