Approach
Breadth-first search
For Maximize Alternating Sum Using Swaps, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 53 lines of C++ from the credited upstream file maximize-alternating-sum-using-swaps.cpp.
- The implementation visibly relies on sequence storage.
- 5 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
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 maxAlternatingSum(vector<int>& nums, vector<vector<int>>& swaps) {8 vector<vector<int>> adj(size(nums));9 for (const auto& s : swaps) {10 adj[s[0]].emplace_back(s[1]);11 adj[s[1]].emplace_back(s[0]);12 }13 vector<bool> lookup(size(adj));14 const auto& bfs = [&](int u) {15 vector<int> q;16 if (lookup[u]) {17 return q;18 }19 lookup[u] = true;20 q.emplace_back(u);21 for (int i = 0; i < size(q); ++i) {22 for (const auto& v : adj[q[i]]) {23 if (lookup[v]) {24 continue;25 }26 lookup[v] = true;27 q.emplace_back(v);28 }29 }30 return q;31 };32 33 int64_t result = accumulate(cbegin(nums), cend(nums), 0ll);34 for (int u = 0; u < size(nums); ++u) {35 const auto& g = bfs(u);36 if (empty(g)) {37 continue;38 }39 const int l = accumulate(cbegin(g), cend(g), 0, [](const auto& total, const auto& x) {40 return total + x % 2;41 });42 vector<int> arr;43 arr.reserve(size(g));44 for (const auto& i : g) {45 arr.emplace_back(nums[i]);46 }47 nth_element(begin(arr), begin(arr) + l, end(arr));48 result -= 2 * accumulate(cbegin(arr), cbegin(arr) + l, 0ll);49 }50 return result;51 }52};53