For example, given the array nums = [10, 5, 2, 6], k = 100
Answer is 8
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
The problem is very similar to subarray with sum of kbut with a small difference, in this case we have to find product.
The problem can be solved by maintaining 2 pointers, very similar to minimum window substring. start,end
pointers will be used to manage the size of window with sum k. The algorithm is as follows:
start
index and product elements along the path, continue mulitply up elements as long it is not greater than kend
index and decrease the value arr[end]
from product.public class Solution {
public int productLessThanK(int[] nums, int k) {
if (k <= 1) return 0;
int prod = 1, ans = 0, left = 0;
for (int right = 0; right < nums.length; right++) {
prod *= nums[right];
while (prod >= k) prod /= nums[left++];
ans += right - left + 1;
}
return ans;
}
}