Count subarrays with element product less than target
Your are given an array of positive integers numbers.
Count and print the number of (contiguous) sub-arrays where the product of all the elements in the sub-array is less than k.
Example 1:
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.
Note:
- 0 < nums.length <= 50000.
- 0 < nums[i] < 1000.
- 0 <= k < 10^6.
goli202084 Changed status to publish
Simple Java code:-
class Solution { public int numSubarrayProductLessThanK(int[] nums, int k) { int product = 1, left = 0, count = 0; for (int right = 0; right < nums.length; right++) { product *= nums[right]; while (product >= k && left < nums.length) product /= nums[left++]; if (right > left - 1) count += (right - left) + 1; } return count; } }
Javascript option
/** * @param {number[]} nums * @param {number} k * @return {number} */ var numSubarrayProductLessThanK = function(nums, k) { var product = 1, left = 0, count = 0; for (var right = 0; right < nums.length; right++) { product *= nums[right]; while (product >= k && left < nums.length) product /= nums[left++]; if (right > left - 1) count += (right - left) + 1; } return count; };
goli202084 Changed status to publish