- 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
- 49 lines of Python from the credited upstream file 3013.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 minimumCost(self, nums: list[int], k: int, dist: int) -> int:6 7 8 windowSum = sum(nums[i] for i in range(1, dist + 2))9 selected = SortedList(nums[i] for i in range(1, dist + 2))10 candidates = SortedList()11 12 def balance() -> int:13 """14 Returns the updated `windowSum` by balancing the multiset `selected` to15 keep the top k - 1 numbers.16 """17 nonlocal windowSum18 while len(selected) < k - 1:19 minCandidate = candidates[0]20 windowSum += minCandidate21 selected.add(minCandidate)22 candidates.remove(minCandidate)23 while len(selected) > k - 1:24 maxSelected = selected[-1]25 windowSum -= maxSelected26 selected.remove(maxSelected)27 candidates.add(maxSelected)28 return windowSum29 30 windowSum = balance()31 minWindowSum = windowSum32 33 for i in range(dist + 2, len(nums)):34 outOfScope = nums[i - dist - 1]35 if outOfScope in selected:36 windowSum -= outOfScope37 selected.remove(outOfScope)38 else:39 candidates.remove(outOfScope)40 if nums[i] < selected[-1]: 41 windowSum += nums[i]42 selected.add(nums[i])43 else:44 candidates.add(nums[i])45 windowSum = balance()46 minWindowSum = min(minWindowSum, windowSum)47 48 return nums[0] + minWindowSum49