From a6dffc2bc7a99cac86453e43b49d3fd4342e0abb Mon Sep 17 00:00:00 2001 From: aucker Date: Tue, 23 Apr 2024 10:04:19 +0800 Subject: [PATCH] update: Apr23 sliding windows --- daily/Apr22.cpp | 44 ++++++++++++++++++++++++++++++++++++++++++++ daily/Apr23.cpp | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 daily/Apr22.cpp create mode 100644 daily/Apr23.cpp diff --git a/daily/Apr22.cpp b/daily/Apr22.cpp new file mode 100644 index 0000000..ab7ecd6 --- /dev/null +++ b/daily/Apr22.cpp @@ -0,0 +1,44 @@ +#include +using namespace std; + +class Solution { + int dfs(int i, vector& nums, vector& memo) { + if (i == 0) { // finish + return 1; + } + int& res = memo[i]; // reference + if (res != -1) { + return res; + } + res = 0; + + for (int x : nums) { + if (x <= i) { + res += dfs(i - x, nums, memo); + } + } + return res; + } + + public: + int combinationSum4(vector& nums, int target) { + vector memo(target + 1, -1); // -1 not computed before + + return dfs(target, nums, memo); + } + + int combinationSum4Op(vector& nums, int target) { + // use unsigned to make overflow still returns normally + // for the overflow dsata, + vector f(target + 1); + f[0] = 1; + for (int i = 1; i <= target; i++) { + for (int x : nums) { + if (x <= i) { + f[i] += f[i - x]; + } + } + } + return f[target]; + } +}; \ No newline at end of file diff --git a/daily/Apr23.cpp b/daily/Apr23.cpp new file mode 100644 index 0000000..9f80d73 --- /dev/null +++ b/daily/Apr23.cpp @@ -0,0 +1,40 @@ +#include +using namespace std; + +class Solution { + public: + int maxSatisfied(vector& customers, vector& grumpy, int minutes) { + int s[2]{}, max_s1 = 0; + for (int i = 0; i < customers.size(); i++) { + s[grumpy[i]] += customers[i]; + if (i < minutes - 1) { // windows size less than minutes + continue; + } + max_s1 = max(max_s1, s[1]); + // leftmost goes out of window + s[1] -= grumpy[i - minutes + 1] ? customers[i - minutes + 1] : 0; + } + return s[0] + max_s1; + } + + int maxSatisfied1(vector& customers, vector& grumpy, int minutes) { + int total = 0; + int n = customers.size(); + for (int i = 0; i < n; i++) { + if (grumpy[i] == 0) { + total += customers[i]; + } + } + int increase = 0; + for (int i = 0; i < minutes; i++) { + increase += customers[i] * grumpy[i]; + } + int maxIncrease = increase; + for (int i = minutes; i < n; i++) { + increase = increase - customers[i - minutes] * grumpy[i - minutes] + + customers[i] * grumpy[i]; + maxIncrease = max(maxIncrease, increase); + } + return total + maxIncrease; + } +}; \ No newline at end of file