Problem solution · C++

Maximum Sum of Edge Values in a Graph

Maximum Sum of Edge Values in a Graph: a C++ solution using sliding window or two pointers. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Sliding window or two pointers
Source
walkccc LeetCode Solutions
Length
73 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Sliding window or two pointers

For Maximum Sum of Edge Values in a Graph, the implementation maintains a moving interval and updates only the information that enters or leaves the window.

  1. Choose the invariant that makes a window valid or useful.
  2. Advance the right boundary and add the new element.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeMaximum Sum of Edge Values in a Graph · C++C++
Use this to learn the idea, then write your own version.
class Solution { public:  long long maxScore(int n, vector<vector<int>>& edges) {    long ans = 0;    vector<vector<int>> graph(n);    vector<int> cycleSizes;  // components where all nodes have degree 2    vector<int> pathSizes;   // components that are not cycleSizes    vector<bool> seen(n);     for (const vector<int>& edge : edges) {      const int u = edge[0];      const int v = edge[1];      graph[u].push_back(v);      graph[v].push_back(u);    }     for (int i = 0; i < n; ++i) {      if (seen[i])        continue;      const vector<int> component = getComponent(graph, i, seen);      const bool allDegree2 = ranges::all_of(          component, [&graph](int u) { return graph[u].size() == 2; });      if (allDegree2)        cycleSizes.push_back(component.size());      else if (component.size() > 1)        pathSizes.push_back(component.size());    }     for (const int cycleSize : cycleSizes) {      ans += calculateScore(n - cycleSize + 1, n, /*isCycle=*/true);      n -= cycleSize;    }     ranges::sort(pathSizes, greater<>());     for (const int pathSize : pathSizes) {      ans += calculateScore(n - pathSize + 1, n, /*isCycle=*/false);      n -= pathSize;    }     return ans;  }  private:  vector<int> getComponent(const vector<vector<int>>& graph, int start,                           vector<bool>& seen) {    vector<int> component = {start};    seen[start] = true;    for (int i = 0; i < component.size(); ++i) {      const int u = component[i];      for (const int v : graph[u]) {        if (seen[v])          continue;        component.push_back(v);        seen[v] = true;      }    }    return component;  }   long calculateScore(int left, int right, bool isCycle) {    deque<long> window = {right, right};    long score = 0;    for (int value = right - 1; value >= left; --value) {      const long windowValue = window.front();      window.pop_front();      score += windowValue * value;      window.push_back(value);    }    return score + window[0] * window[1] * isCycle;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗