- 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
- 50 lines of Python from the credited upstream file 3510.py.
- The implementation visibly relies on sequence storage.
- No explicit 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.
1from sortedcontainers import SortedList2 3 4class Solution:5 def minimumPairRemoval(self, nums: list[int]) -> int:6 n = len(nums)7 ans = 08 inversionsCount = sum(nums[i + 1] < nums[i] for i in range(n - 1))9 nextIndices = [i + 1 for i in range(n)]10 prevIndices = [i - 1 for i in range(n)]11 pairSums = SortedList((a + b, i)12 for i, (a, b) in enumerate(itertools.pairwise(nums)))13 14 while inversionsCount > 0:15 ans += 116 smallestPair = pairSums.pop(0)17 pairSum, currIndex = smallestPair18 nextIndex = nextIndices[currIndex]19 prevIndex = prevIndices[currIndex]20 21 if prevIndex >= 0:22 oldPairSum = nums[prevIndex] + nums[currIndex]23 newPairSum = nums[prevIndex] + pairSum24 pairSums.remove((oldPairSum, prevIndex))25 pairSums.add((newPairSum, prevIndex))26 if nums[prevIndex] > nums[currIndex]:27 inversionsCount -= 128 if nums[prevIndex] > pairSum:29 inversionsCount += 130 31 if nums[nextIndex] < nums[currIndex]:32 inversionsCount -= 133 34 nextNextIndex = nextIndices[nextIndex] if nextIndex < n else n35 if nextNextIndex < n:36 oldPairSum = nums[nextIndex] + nums[nextNextIndex]37 newPairSum = pairSum + nums[nextNextIndex]38 pairSums.remove((oldPairSum, nextIndex))39 pairSums.add((newPairSum, currIndex))40 if nums[nextNextIndex] < nums[nextIndex]:41 inversionsCount -= 142 if nums[nextNextIndex] < pairSum:43 inversionsCount += 144 prevIndices[nextNextIndex] = currIndex45 46 nextIndices[currIndex] = nextNextIndex47 nums[currIndex] = pairSum48 49 return ans50