Solution 8: Minimal Length Subarray
Given an array of positive integers and a positive integer target value, return the minimal length of a subarray which has a sum greater than or equal to target. If there is no such subarray in the array, return 0.
def min_sub_array_len(target, nums)
sub_array_length = 0
start_index = 0
end_index = 0
loop do
sub_array_sum = get_sum(nums, start_index, end_index)
if (sub_array_sum < target)
end_index += 1
elsif (sub_array_sum > target)
start_index += 1
else
this_array_length = (end_index - start_index) + 1
sub_array_length = if sub_array_length == 0
this_array_length
else
sub_array_length < this_array_length ? sub_array_length : this_array_length
end
end_index += 1
end
if (end_index >= nums.length)
break
end
end
sub_array_length
end
def get_sum(array, start_index, end_index)
sum = 0
for number in array[start_index..end_index]
sum += number
end
sum
end