Leetcode 713 Subarray Product Less Than K
Input: nums = [10,5,2,6], k = 100
Output: 8
Explanation: The 8 subarrays that have product less than 100 are:
[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]
Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.
Input: nums = [1,2,3], k = 0
Output: 0
- Input: nums = [10, 5, 2, 6], k = 100
======== (End for loop, r = 0 snapshot) ============= [10, 5, 2, 6] r l prod = 10 cnt += 1
======== (End for loop, r = 1 snapshot) ============= [10, 5, 2, 6] r l prod = 50 cnt += 2
======== (r = 2, prod >= k snapshot) ================
[10, 5, 2, 6]
r
l
prod = 100, >= k,
keep moving l till < k
======== (End for loop, r = 2 snapshot) =============
[10, 5, 2, 6]
r
l
prod = 10
cnt += 2
======== (End for loop, r = 3 snapshot) =============
[10, 5, 2, 6]
r
l
prod = 60
cnt += 3
class Solution(object):
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
left, prod, count = 0, 1, 0
for right in range(len(nums)):
prod *= nums[right]
while prod >= k and left <= right:
prod /= nums[left]
left += 1
count += right - left + 1
return count