- 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
- 67 lines of Python from the credited upstream file 3385.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.
1class Solution:2 def findMinimumTime(self, strength: list[int]) -> int:3 costs = [[(s + turn - 1) turn4 for s in strength]5 for turn in range(1, len(strength) + 1)]6 return self._hungarian(costs)[-1]7 8 def _hungarian(self, costs):9 """10 Returns an array `res` of length n (costs.length), with `res[i]` equaling11 the minimum cost to assign the first (i + 1) turns to the first (i + 1)12 locks using Hungarian algorithm, where costs[i][j] is the energy required13 to break j-th lock in i-th turn.14 15 https:en.wikipedia.org/wiki/Hungarian_algorithm16 """17 numLocks = len(costs)18 turnPotentials = [0] * numLocks19 lockPotentials = [0] * (numLocks + 1)20 lockAssignments = [-1] * (numLocks + 1)21 res = []22 23 for currentTurn in range(numLocks):24 currentLock = numLocks25 lockAssignments[currentLock] = currentTurn26 minReducedCosts = [math.inf] * (numLocks + 1)27 previousLockAssignments = [-1] * (numLocks + 1)28 locksInOptimalPath = [False] * (numLocks + 1)29 30 while lockAssignments[currentLock] != -1:31 locksInOptimalPath[currentLock] = True32 assignedTurn = lockAssignments[currentLock]33 minCostDelta = math.inf34 nextLock = None35 36 for lock in range(numLocks):37 if not locksInOptimalPath[lock]:38 reducedCost = (39 costs[assignedTurn][lock] -40 turnPotentials[assignedTurn] -41 lockPotentials[lock]42 )43 oldMin = minReducedCosts[lock]44 minReducedCosts[lock] = min(oldMin, reducedCost)45 if minReducedCosts[lock] < oldMin:46 previousLockAssignments[lock] = currentLock47 if minReducedCosts[lock] < minCostDelta:48 minCostDelta = minReducedCosts[lock]49 nextLock = lock50 51 for lock in range(numLocks + 1):52 if locksInOptimalPath[lock]:53 turnPotentials[lockAssignments[lock]] += minCostDelta54 lockPotentials[lock] -= minCostDelta55 else:56 minReducedCosts[lock] -= minCostDelta57 58 currentLock = nextLock59 60 while currentLock != numLocks:61 lockAssignments[currentLock] = lockAssignments[previousLockAssignments[currentLock]]62 currentLock = previousLockAssignments[currentLock]63 64 res.append(-lockPotentials[numLocks])65 66 return res67