- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 57 lines of C++ from the credited upstream file sum-of-weighted-modes-in-subarrays.cpp.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, work queue.
- 3 loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 long long modeWeight(vector<int>& nums, int k) {8 unordered_map<int, int> cnt;9 set<pair<int, int>> bst;10 const auto& add = [&](int x, int diff) {11 if (cnt[x]) {12 bst.erase(pair(-cnt[x], x));13 }14 cnt[x] += diff;15 if (cnt[x]) {16 bst.emplace(-cnt[x], x);17 } else {18 cnt.erase(x);19 }20 };21 22 int64_t result = 0;23 for (int i = 0; i < size(nums); ++i) {24 add(nums[i], +1);25 if (i >= k - 1) {26 result += static_cast<int64_t>(-cbegin(bst)->first) * cbegin(bst)->second;27 add(nums[i - k + 1], -1);28 }29 }30 return result;31 }32};33 34353637class Solution2 {38public:39 long long modeWeight(vector<int>& nums, int k) {40 unordered_map<int, int> cnt;41 priority_queue<pair<int, int>> max_heap;42 int64_t result = 0;43 for (int i = 0; i < size(nums); ++i) {44 ++cnt[nums[i]];45 max_heap.emplace(cnt[nums[i]], -nums[i]);46 if (i >= k - 1) {47 while (max_heap.top().first != cnt[-max_heap.top().second]) {48 max_heap.pop();49 }50 result += static_cast<int64_t>(max_heap.top().first) * -max_heap.top().second;51 --cnt[nums[i - k + 1]];52 }53 }54 return result;55 }56};57