0713 Subarray with a product less than k

0713 Subarray with a product less than k#

def numSubarrayProductLessThanK(nums, k):
    # moving window
    # cannot use sort because of the order of number matters here
    n = len(nums)
    res = []
    
    # initialize at each step
    l, r = 0, 0
    prod = nums[l]

    # moving window
    while r < n:
        # update result
        if prod < k:
            if len(list(nums[l:r+1]))>0:
                res.append(list(nums[l:r+1])) 
        
        # expand window
        if prod < k:
            # move window
            r += 1

            # update window state
            if r < n:
                prod *= nums[r]

                if nums[r] < k:
                    res.append([nums[r]])
        else:
            # shrink window
            while prod >= k:
                l += 1
                # update window state
                prod = prod / nums[l-1]

    # in case the last subarrays are less than k
    if l < n and prod < k:
        while l < n-1:
            l += 1
            res.append(list(nums[l:]))

    return len(res)


print(numSubarrayProductLessThanK([10,5,2,6], 100))
            
9