Skip to content

Commit b21fb2f

Browse files
committed
713
1 parent c492eb7 commit b21fb2f

File tree

1 file changed

+49
-0
lines changed
  • leetcode/713. Subarray Product Less Than K

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# [713. Subarray Product Less Than K (Medium)](https://leetcode.com/problems/subarray-product-less-than-k/)
2+
3+
<p>Your are given an array of positive integers <code>nums</code>.</p>
4+
<p>Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less than <code>k</code>.</p>
5+
6+
<p><b>Example 1:</b><br>
7+
</p><pre><b>Input:</b> nums = [10, 5, 2, 6], k = 100
8+
<b>Output:</b> 8
9+
<b>Explanation:</b> The 8 subarrays that have product less than 100 are: [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6].
10+
Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.
11+
</pre>
12+
<p></p>
13+
14+
<p><b>Note:</b>
15+
</p><li><code>0 &lt; nums.length &lt;= 50000</code>.</li>
16+
<li><code>0 &lt; nums[i] &lt; 1000</code>.</li>
17+
<li><code>0 &lt;= k &lt; 10^6</code>.</li>
18+
<p></p>
19+
20+
**Related Topics**:
21+
[Array](https://leetcode.com/tag/array/), [Two Pointers](https://leetcode.com/tag/two-pointers/)
22+
23+
**Similar Questions**:
24+
* [Maximum Product Subarray (Medium)](https://leetcode.com/problems/maximum-product-subarray/)
25+
* [Maximum Size Subarray Sum Equals k (Medium)](https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/)
26+
* [Subarray Sum Equals K (Medium)](https://leetcode.com/problems/subarray-sum-equals-k/)
27+
* [Two Sum Less Than K (Easy)](https://leetcode.com/problems/two-sum-less-than-k/)
28+
29+
## Solution 1. Sliding Window
30+
31+
```cpp
32+
// OJ: https://leetcode.com/problems/subarray-product-less-than-k/
33+
// Author: github.com/lzl124631x
34+
// Time: O(N)
35+
// Space: O(1)
36+
class Solution {
37+
public:
38+
int numSubarrayProductLessThanK(vector<int>& A, int k) {
39+
if (k == 0) return 0;
40+
int N = A.size(), i = 0, j = 0, p = 1, ans = 0;
41+
while (j < N) {
42+
p *= A[j++];
43+
while (i < j && p >= k) p /= A[i++];
44+
ans += j - i;
45+
}
46+
return ans;
47+
}
48+
};
49+
```

0 commit comments

Comments
 (0)