Skip to main content
Back to problems
#3364
Easy Algorithms

Minimum positive sum subarray

Array Sliding Window Prefix Sum
44.9% acceptance
Feb 24, 2026
156
37
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.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn minimum_sum_subarray(nums: Vec<i32>, l: i32, r: i32) -> i32 {
    let n = nums.len();
    let (l, r) = (l as usize, r as usize);
    let mut ans = i32::MAX;
    // Brute force O(n^2): all subarrays of length in [l,r]
    for i in 0..n {
      let mut sum = 0;
      for j in i..n {
        sum += nums[j];
        let len = j - i + 1;
        if len >= l && len <= r && sum > 0 {
          ans = ans.min(sum);
        }
        if len >= r { break; }
      }
    }
    if ans == i32::MAX { -1 } else { ans }
  }
}