Your are given an array of positive integers nums
.
Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray 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
.Related Topics:
Array, Two Pointers
Similar Questions:
- Maximum Product Subarray (Medium)
- Maximum Size Subarray Sum Equals k (Medium)
- Subarray Sum Equals K (Medium)
- Two Sum Less Than K (Easy)
Check out "C++ Maximum Sliding Window Cheatsheet Template!".
state
:prod
is the product of the numbers in windowinvalid
:prod >= k
is invalid.
Note that since we want to make sure the window [i, j]
is valid at the end of the for
loop, we need i <= j
check for the inner for
loop. i == j + 1
means this window is empty.
Each maximum window [i, j]
can generate j - i + 1
valid subarrays, so we need to add j - i + 1
to the answer.
// OJ: https://leetcode.com/problems/subarray-product-less-than-k/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
int numSubarrayProductLessThanK(vector<int>& A, int k) {
if (k == 0) return 0;
long i = 0, j = 0, N = A.size(), prod = 1, ans = 0;
for (; j < N; ++j) {
prod *= A[j];
while (i <= j && prod >= k) prod /= A[i++];
ans += j - i + 1;
}
return ans;
}
};