Subarray Product Less Than K
Problem statement
Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k.
Example 1:
Input: nums = [10,5,2,6], k = 100Output: 8Explanation: 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.
Example 2:
Input: nums = [1,2,3], k = 0Output: 0
Constraints:
1 <= nums.length <= 3 * 1041 <= nums[i] <= 10000 <= k <= 106
My solution
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var numSubarrayProductLessThanK = function(nums, k) {
if (nums === null || nums.length === 0) {
return 0
}
if (k <= 1) {
return 0
}
let start = 0;
let count = 0;
let product = 1;
for (let end = 0; end < nums.length; end++) {
product *= nums[end];
while (product >= k && start <= end) {
product /= nums[start++]
}
count += end - start + 1;
// console.log(product, count)
}
return count;
};