Write a function that accepts two parameters an array of positive integers and a positive integer.
This function should return the minimal length of the contiguous subarray of which the sum is greater than or equal to the integer passed to the function. If there isn't one return 0.
ex-
fun([2,3,1,2,4,3] , 7) // 2 because [4,3] is smallest subarray
fun([3,1,7,11,2,9,8,21,62,33,19],52). // 1 because 62 is greatest
Answers
Answer:
ex-
fun([2,3,1,2,4,3] , 7) // 2 because [4,3] is smallest subarray
fun([3,1,7,11,2,9,8,21,62,33,19],52). // 1 because 62 is greatest
Explanation:
A function that accepts two parameters an array of positive integers is given below.
import sys
def findSmallestSubarrayLen(A, k):
windowSum = 0
# stores the result in length variable
length = sys.maxsize
# index to divde the array into left and right
left = 0
# `[left…right]` that is the array
for right in range(len(A)):
# include the current element in the window variable
windowSum += A[right]
# the window variable becomes unstable if its sum becomes more than `k`
while windowSum > k and left <= right:
# update the result if the current is the array length is less than the
# minimum found so far
length = min(length, right - left + 1)
# remove elements from the array's left side till the array size
# becomes stable again
windowSum -= A[left]
left = left + 1
#for invalid input
if length == sys.maxsize:
return 0
# return result the length of array
return length
if __name__ == '__main__':
# a list of positive numbers
A = [1, 2, 3, 4, 5, 6, 7, 8]
k = 21
# find the length of the smallest subarray
length = findSmallestSubarrayLen(A, k)
if length != sys.maxsize:
print("The smallest subarray length is", length)
else:
print("No subarray exists")