diff --git a/cpp/2305/LC230506.cpp b/cpp/2305/LC230506.cpp new file mode 100644 index 0000000..e84bb0d --- /dev/null +++ b/cpp/2305/LC230506.cpp @@ -0,0 +1,34 @@ +#include +#include + +/** + * 1498. Number of Subsequences That Satisfy the Given Sum Condition + * + * You are given an array of integers nums and an integer target. + * Return the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal to target. Since the answer may be too large, return it modulo 109 + 7. + */ + +class LC230506 { +public: + static int numSubseq(std::vector&, int) noexcept; +}; + +constexpr int pwr2(int x) noexcept { + unsigned long long cur = 2, ret = 1; + for (; x; (x >>= 1), (cur = (cur * cur) % 1'000'000'007)) + if (x & 1) + ret = (ret * cur) % 1'000'000'007; + return ret % 1'000'000'007; +} + +int LC230506::numSubseq(std::vector& n, int target) noexcept { + std::sort(n.begin(), n.end()); + int ret = 0; + for (int l = 0, r = n.size() - 1; l < n.size(); ++l) { + for (; r > 0 && n[l] + n[r] > target; --r); + ret = (ret + ((!r || r <= l) ? ((n[l] << 1) <= target) : pwr2(r - l))) % 1'000'000'007; + if ((n[l] << 1) > target) + return ret; + } + return ret; +} diff --git a/cpp/2305/defs.h b/cpp/2305/defs.h index bb54d22..f84b37b 100644 --- a/cpp/2305/defs.h +++ b/cpp/2305/defs.h @@ -60,4 +60,9 @@ public: static int maxVowels(const std::string&, int) noexcept; }; +class LC230506 { +public: + static int numSubseq(std::vector&, int) noexcept; +}; + #endif //LEETCODE_CPP_DEFS_H diff --git a/cpp/2305/main.cpp b/cpp/2305/main.cpp index f210098..7717319 100644 --- a/cpp/2305/main.cpp +++ b/cpp/2305/main.cpp @@ -12,8 +12,7 @@ std::ostream& operator<<(std::ostream& os, const std::vector& x) noexcept { } int main() { - std::cout << LC230504CN::maxTotalFruits({ - {0,3},{6,4},{8,5} - }, 3,2); + std::vector arr {2,3,3,4,6,7}; + std::cout << LC230506::numSubseq(arr,12); return 0; }