1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00
LeetCode/cpp/subarray-product-less-than-k.cpp
Matej Focko 10e24a7593
cpp: add «713. Subarray Product Less Than K»
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-03-27 22:10:03 +01:00

43 lines
875 B
C++

#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