Skip to content

Instantly share code, notes, and snippets.

@drem-darios
Last active February 9, 2020 06:30
Show Gist options
  • Save drem-darios/c5a7c9bd84039cd17819f733d80d45a8 to your computer and use it in GitHub Desktop.
Save drem-darios/c5a7c9bd84039cd17819f733d80d45a8 to your computer and use it in GitHub Desktop.
Given an array of positive numbers and a positive number ‘S’, find the length of the smallest contiguous subarray whose sum is greater than or equal to ‘S’. Return 0, if no such subarray exists.
import math
def smallest_subarray_with_given_sum(s, arr):
subArrayStart = 0
resultArraySize = math.inf
subArraySum = 0
for subArrayEnd in range(0, len(arr)):
subArraySum += arr[subArrayEnd]
while subArraySum >= s:
if resultArraySize > subArrayEnd - subArrayStart + 1:
resultArraySize = subArrayEnd - subArrayStart + 1
subArraySum -= arr[subArrayStart]
subArrayStart+=1
if resultArraySize == math.inf:
return 0
return resultArraySize
def main():
print("Smallest subarray length: " + str(smallest_subarray_with_given_sum(7, [2, 1, 5, 2, 3, 2])))
print("Smallest subarray length: " + str(smallest_subarray_with_given_sum(7, [2, 1, 5, 2, 8])))
print("Smallest subarray length: " + str(smallest_subarray_with_given_sum(8, [3, 4, 1, 1, 6])))
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment