Last active
February 9, 2020 06:30
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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