1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-19 17:56:55 +02:00

cpp: add «713. Subarray Product Less Than K»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-03-27 22:10:03 +01:00
parent 5c3727b0d9
commit 10e24a7593
Signed by: mfocko
GPG key ID: 7C47D46246790496

View 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