[LeetCode] Subarray Product Less Than K

713. Subarray Product Less Than K

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int numSubarrayProductLessThanK(vector<int>& nums, int k) {
long long p = 1;
int res = 0, n = nums.size();
for(int l = 0, r = 0; l < n; l++) {
r = max(r,l);
while(r < n and p < k) {
p *= nums[r++];
}
if(r!=l)
res += (r - l - (p >= k));
p /= nums[l];
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/26/PS/LeetCode/subarray-product-less-than-k/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.