Created
May 20, 2018 20:06
-
-
Save lopezm1/c1a1923ea2fc62eab76900e8c5fd97ee to your computer and use it in GitHub Desktop.
# Given an array of integers and a number x, find the smallest subarray with sum greater than the given value.
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
# Given an array of integers and a number x, find the smallest subarray with sum greater than the given value. | |
""" | |
arr[] = {1, 4, 45, 6, 0, 19} | |
x = 51 | |
Output: 3 | |
Minimum length subarray is {4, 45, 6} | |
""" | |
save = None | |
def checkArray(arr, val): | |
global save | |
if sum(arr) > val: | |
print("----HIT: ", arr, sum(arr)) | |
if save is None: | |
print("FIRST SAVE", arr) | |
save = arr | |
elif len(arr) < len(save): | |
print("~~~SAVE~~~", arr) | |
save = arr | |
def smallestArray(arr, val): | |
global save | |
for i in range(0, len(arr)): | |
tmp = [] # new subarray at each index | |
for x in range(i, len(arr)): | |
tmp.append(arr[x]) | |
checkArray(list(tmp), val) # pass a list so that the nums are immutable | |
print("FINAL ANSWER: ", save) | |
# smallestArray([1, 4, 45, 6, 0, 19], 51) | |
smallestArray([1, 11, 100, 1, 0, 200, 3, 2, 1, 250], 280) | |
# smallestArray([1, 2, 4], 8) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
----HIT: [1, 11, 100, 1, 0, 200] 313
FIRST SAVE [1, 11, 100, 1, 0, 200]
----HIT: [1, 11, 100, 1, 0, 200, 3] 316
----HIT: [1, 11, 100, 1, 0, 200, 3, 2] 318
----HIT: [1, 11, 100, 1, 0, 200, 3, 2, 1] 319
----HIT: [1, 11, 100, 1, 0, 200, 3, 2, 1, 250] 569
----HIT: [11, 100, 1, 0, 200] 312