From 62fde321d6a0fdc18961072978a88debf19e4f5d Mon Sep 17 00:00:00 2001 From: chayan das Date: Wed, 5 Nov 2025 23:54:17 +0530 Subject: [PATCH] Create 3321. Find X-Sum of All K-Long Subarrays II --- 3321. Find X-Sum of All K-Long Subarrays II | 78 +++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 3321. Find X-Sum of All K-Long Subarrays II diff --git a/3321. Find X-Sum of All K-Long Subarrays II b/3321. Find X-Sum of All K-Long Subarrays II new file mode 100644 index 0000000..c546513 --- /dev/null +++ b/3321. Find X-Sum of All K-Long Subarrays II @@ -0,0 +1,78 @@ +class Solution { +public: + using P = pair; + struct Cmp { + bool operator()(const P& a, const P& b) const { + if (a.first != b.first) return a.first > b.first; + return a.second > b.second; + } + }; + + vector findXSum(vector& nums, int k, int x) { + int n = (int)nums.size(); + vector ans(n - k + 1); + + unordered_map cnt; + cnt.reserve(n * 1); + + set top, rest; + long long topSum = 0; + + auto pull = [&](int v, int f){ + P key{f, v}; + auto it = top.find(key); + if (it != top.end()){ + topSum -= 1LL * v * f; + top.erase(it); + } else { + auto jt = rest.find(key); + if (jt != rest.end()) rest.erase(jt); + } + }; + auto pushToTop = [&](int v, int f){ + top.insert({f, v}); + topSum += 1LL * v * f; + }; + + auto insertVal = [&](int v){ + int f = cnt[v]; + if (f) pull(v, f); + ++f; cnt[v] = f; + pushToTop(v, f); + if ((int)top.size() > x){ + auto it = prev(top.end()); + topSum -= 1LL * it->first * it->second; + rest.insert(*it); + top.erase(it); + } + }; + + auto eraseVal = [&](int v){ + auto itc = cnt.find(v); + if (itc == cnt.end()) return; + int f = itc->second; + pull(v, f); + if (--f == 0){ + cnt.erase(itc); + } else { + cnt[v] = f; + rest.insert({f, v}); + } + if ((int)top.size() < x && !rest.empty()){ + auto best = rest.begin(); + topSum += 1LL * best->first * best->second; + top.insert(*best); + rest.erase(best); + } + }; + + for (int i = 0; i < k; ++i) insertVal(nums[i]); + ans[0] = topSum; + for (int i = k; i < n; ++i){ + eraseVal(nums[i-k]); + insertVal(nums[i]); + ans[i - k + 1] = topSum; + } + return ans; + } +};