Skip to content

Commit 83484bb

Browse files
committed
add numSubarrayProductLessThanK in cpp
1 parent 120476f commit 83484bb

File tree

1 file changed

+49
-0
lines changed

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+
/**
2+
Given an array of integers nums and an integer k,
3+
return the number of contiguous subarrays where the product of all the elements in the subarray is
4+
strictly less than k.
5+
6+
The provided code defines a Java class Solution with a method numSubarrayProductLessThanK that counts the number
7+
of subarrays in an input array nums whose product is less than a given threshold k. It uses a sliding window
8+
approach to efficiently compute this count.
9+
10+
Time Complexity:
11+
12+
The code iterates through the nums array once, using two pointers (startWindow and endWindow) to define the
13+
sliding window. This results in a time complexity of O(N), where N is the length of the input array nums.
14+
Space Complexity:
15+
16+
The code uses a constant amount of additional space to store integer variables (startWindow, product, and count).
17+
Therefore, the space complexity is O(1), which means it is independent of the size of the input array.
18+
*/
19+
20+
#include <vector>
21+
22+
class Solution {
23+
public:
24+
int numSubarrayProductLessThanK(std::vector<int>& nums, int k) {
25+
int startWindow = 0; // The left end of the sliding window
26+
int product = 1; // Initialize product to 1 to accumulate the product
27+
int count = 0; // Count of subarrays with a product less than k
28+
29+
// Iterate through the array using a sliding window approach
30+
for (int endWindow = 0; endWindow < nums.size(); endWindow++) {
31+
// Multiply the current element to the product
32+
product *= nums[endWindow];
33+
34+
// Shrink the window by moving the start pointer as long as the product is greater than or equal to k
35+
while (startWindow <= endWindow && product >= k) {
36+
// Divide the product by the element at the start of the window
37+
product /= nums[startWindow];
38+
// Move the start of the window to the right
39+
startWindow++;
40+
}
41+
42+
// Update the count with the number of valid subarrays within the current window
43+
count += endWindow - startWindow + 1;
44+
}
45+
46+
// Return the count, which represents the number of subarrays with a product less than k
47+
return count;
48+
}
49+
};

0 commit comments

Comments
 (0)