Last active
December 18, 2020 10:21
-
-
Save codecakes/068a1cc98abaac017bea166b4758c967 to your computer and use it in GitHub Desktop.
find the length of the smallest contiguous subarray whose sum is greater than or equal to S
This file contains hidden or 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
def smallest_subarray_with_given_sum(s, arr): | |
min_ct = float('inf') | |
t_head = head_idx = 0 | |
running_sum = 0 | |
t_sum = 0 | |
for tail_idx, num in enumerate(arr): | |
running_sum += num | |
while running_sum >= s: | |
min_ct = min(min_ct, tail_idx - head_idx+1) | |
running_sum -= arr[head_idx] | |
head_idx += 1 | |
return min_ct | |
def smallest_subarray_with_given_sum_not_better(s, arr): | |
print("max sum={s} and array = {arr}".format(s=s, arr=arr)) | |
min_ct = float('inf') | |
t_head = head_idx = 0 | |
running_sum = 0 | |
t_sum = 0 | |
for tail_idx, num in enumerate(arr): | |
running_sum += num | |
while running_sum >= s: | |
print("head_idx={} tail_idx={}".format(head_idx, tail_idx)) | |
min_ct = min(min_ct, tail_idx - head_idx+1) | |
print("min range is {}".format(min_ct)) | |
t_head = head_idx | |
t_sum = running_sum | |
while t_sum >= s and t_sum-arr[t_head] >= s and t_head < tail_idx: | |
t_sum -= arr[t_head] | |
t_head += 1 | |
min_ct = min(min_ct, tail_idx - t_head+1) | |
print("t_head is {} tail_idx is {} t_sum is {}".format(t_head, tail_idx, t_sum)) | |
print("min range after adjustment is {}".format(min_ct)) | |
running_sum -= arr[head_idx] | |
head_idx += 1 | |
print("="*20) | |
return min_ct |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment