- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 73 lines of C++ from the credited upstream file 3510.cpp.
- The implementation visibly relies on sequence storage, ordered lookup.
- 4 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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 int minimumPairRemoval(vector<int>& nums) {4 const int n = nums.size();5 int ans = 0;6 int inversionsCount = 0;7 vector<int> nextIndices(n);8 vector<int> prevIndices(n);9 vector<long> values(nums.begin(), nums.end());10 11 12 auto comp = [](const pair<long, int>& a, const pair<long, int>& b) {13 return a.first < b.first || (a.first == b.first && a.second < b.second);14 };15 set<pair<long, int>, decltype(comp)> pairSums(comp);16 17 for (int i = 0; i < n; ++i) {18 nextIndices[i] = i + 1;19 prevIndices[i] = i - 1;20 }21 22 for (int i = 0; i < n - 1; ++i)23 pairSums.insert({(long)nums[i] + nums[i + 1], i});24 25 for (int i = 0; i < n - 1; ++i)26 if (nums[i + 1] < nums[i])27 ++inversionsCount;28 29 while (inversionsCount > 0) {30 ++ans;31 auto smallestPair = *pairSums.begin();32 pairSums.erase(pairSums.begin());33 34 const long pairSum = smallestPair.first;35 const int currIndex = smallestPair.second;36 const int nextIndex = nextIndices[currIndex];37 const int prevIndex = prevIndices[currIndex];38 39 if (prevIndex >= 0) {40 const long oldPairSum = values[prevIndex] + values[currIndex];41 const long newPairSum = values[prevIndex] + pairSum;42 pairSums.erase({oldPairSum, prevIndex});43 pairSums.insert({newPairSum, prevIndex});44 if (values[prevIndex] > values[currIndex])45 --inversionsCount;46 if (values[prevIndex] > pairSum)47 ++inversionsCount;48 }49 50 if (values[nextIndex] < values[currIndex])51 --inversionsCount;52 53 const int nextNextIndex = (nextIndex < n) ? nextIndices[nextIndex] : n;54 if (nextNextIndex < n) {55 const long oldPairSum = values[nextIndex] + values[nextNextIndex];56 const long newPairSum = pairSum + values[nextNextIndex];57 pairSums.erase({oldPairSum, nextIndex});58 pairSums.insert({newPairSum, currIndex});59 if (values[nextNextIndex] < values[nextIndex])60 --inversionsCount;61 if (values[nextNextIndex] < pairSum)62 ++inversionsCount;63 prevIndices[nextNextIndex] = currIndex;64 }65 66 nextIndices[currIndex] = nextNextIndex;67 values[currIndex] = pairSum;68 }69 70 return ans;71 }72};73