My first approach was to gradually increase the window_size and check if the subarray has sum >= target. And boom, Time Limit Exceeded🥲 it turned out to be too slow
It’s a brute force method, so it runs through redundant cases that we can exclude by traversing our sliding window.
Start with window_size = 0, and increase it until you find the first matching window_size. Then, exclude the leftmost element, one by one, to find the minimum window_size.
The main idea is that if the sum of [i, k] is greater than or equal to the target, we don’t need to check [i, k+m]. If sum < target, slide the window to the right by 1, and repeat the process.
209_minimum_size_subarray_sum.rb
require'minitest/autorun'
# @param {Integer} target
# @param {Integer[]} nums
# @return {Integer}
def_209_min_sub_array_len_tle(target,nums)
window_size=0
n= nums.length
start_sum=0
while window_size < n
window_size+=1
start_sum+= nums[window_size -1]
sum= start_sum
i=0
while i <= n - window_size
if i >0
sum= sum - nums[i -1]+ nums[i + window_size -1]
end
return window_size if sum >= target
i+=1
end
end
0
end
def_209_min_sub_array_len(target,nums)
left=0
sum=0
min_window_size=Float::INFINITY
n= nums.length
right=0
while right < n
sum+= nums[right]
while sum >= target
sum-= nums[left]
min_window_size=[min_window_size, right - left +1].min