- 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
- 73 lines of C++ from the credited upstream file 3547.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 7 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.
1class Solution {2 public:3 long long maxScore(int n, vector<vector<int>>& edges) {4 long ans = 0;5 vector<vector<int>> graph(n);6 vector<int> cycleSizes; 7 vector<int> pathSizes; 8 vector<bool> seen(n);9 10 for (const vector<int>& edge : edges) {11 const int u = edge[0];12 const int v = edge[1];13 graph[u].push_back(v);14 graph[v].push_back(u);15 }16 17 for (int i = 0; i < n; ++i) {18 if (seen[i])19 continue;20 const vector<int> component = getComponent(graph, i, seen);21 const bool allDegree2 = ranges::all_of(22 component, [&graph](int u) { return graph[u].size() == 2; });23 if (allDegree2)24 cycleSizes.push_back(component.size());25 else if (component.size() > 1)26 pathSizes.push_back(component.size());27 }28 29 for (const int cycleSize : cycleSizes) {30 ans += calculateScore(n - cycleSize + 1, n, true);31 n -= cycleSize;32 }33 34 ranges::sort(pathSizes, greater<>());35 36 for (const int pathSize : pathSizes) {37 ans += calculateScore(n - pathSize + 1, n, false);38 n -= pathSize;39 }40 41 return ans;42 }43 44 private:45 vector<int> getComponent(const vector<vector<int>>& graph, int start,46 vector<bool>& seen) {47 vector<int> component = {start};48 seen[start] = true;49 for (int i = 0; i < component.size(); ++i) {50 const int u = component[i];51 for (const int v : graph[u]) {52 if (seen[v])53 continue;54 component.push_back(v);55 seen[v] = true;56 }57 }58 return component;59 }60 61 long calculateScore(int left, int right, bool isCycle) {62 deque<long> window = {right, right};63 long score = 0;64 for (int value = right - 1; value >= left; --value) {65 const long windowValue = window.front();66 window.pop_front();67 score += windowValue * value;68 window.push_back(value);69 }70 return score + window[0] * window[1] * isCycle;71 }72};73