From 10e24a75933d779743d604a6b3209f8ab684d472 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Wed, 27 Mar 2024 22:10:03 +0100 Subject: [PATCH] =?UTF-8?q?cpp:=20add=20=C2=AB713.=20Subarray=20Product=20?= =?UTF-8?q?Less=20Than=20K=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- cpp/subarray-product-less-than-k.cpp | 43 ++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 cpp/subarray-product-less-than-k.cpp diff --git a/cpp/subarray-product-less-than-k.cpp b/cpp/subarray-product-less-than-k.cpp new file mode 100644 index 0000000..5dad3c0 --- /dev/null +++ b/cpp/subarray-product-less-than-k.cpp @@ -0,0 +1,43 @@ +#include + +class Solution { + public: + int numSubarrayProductLessThanK(const std::vector &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 + +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