cpp: add «713. Subarray Product Less Than K»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
5c3727b0d9
commit
10e24a7593
1 changed files with 43 additions and 0 deletions
43
cpp/subarray-product-less-than-k.cpp
Normal file
43
cpp/subarray-product-less-than-k.cpp
Normal file
|
@ -0,0 +1,43 @@
|
|||
#include <vector>
|
||||
|
||||
class Solution {
|
||||
public:
|
||||
int numSubarrayProductLessThanK(const std::vector<int> &nums, int k) {
|
||||
if (k <= 1) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
int count = 0;
|
||||
int product = 1;
|
||||
for (std::size_t i = 0, j = 0; j < nums.size(); ++j) {
|
||||
product *= nums[j];
|
||||
|
||||
for (; product >= k; ++i) {
|
||||
product /= nums[i];
|
||||
}
|
||||
|
||||
count += j - i + 1;
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
};
|
||||
|
||||
#ifdef _MF_TEST
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
TEST(examples, _1) {
|
||||
Solution s;
|
||||
EXPECT_EQ(s.numSubarrayProductLessThanK(std::vector{10, 5, 2, 6}, 100), 8);
|
||||
}
|
||||
|
||||
TEST(examples, _2) {
|
||||
Solution s;
|
||||
EXPECT_EQ(s.numSubarrayProductLessThanK(std::vector{1, 2, 3}, 0), 0);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
#endif
|
Loading…
Reference in a new issue