Sum of shortest subarrays

topic

input:[2,3,1,2,4,3],7
output: 1,2,4

Ideas

Sliding window. When sum is greater than 7, it is a legal window, and less than 7 is an illegal window. Find the minimum value array greater than or equal to 7 under the legal window.

Code

def minsubset(nums,k):
    i = 0
    j = 0
    sum = 0
    res = float('inf')
    while j<len(nums):
        if sum<7:
            sum += nums[j]
            j += 1
        else:
            if sum<res:
                t = nums[i:j]
            res = min(res,sum)
            sum = sum - nums[i]
            i +=1
    return t

Guess you like

Origin blog.csdn.net/aaaqqq1234/article/details/107822380