- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 79 lines of Java from the credited upstream file 3385.java.
- The implementation visibly relies on sequence storage.
- 7 loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
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 int findMinimumTime(int[] strength) {3 int[][] costs = new int[strength.length][strength.length];4 for (int turn = 1; turn <= strength.length; ++turn)5 for (int j = 0; j < strength.length; j++)6 costs[turn - 1][j] = (strength[j] + turn - 1) / turn;7 return hungarian(costs)[costs.length - 1];8 }9 10 11 private boolean updateMinimum(int[] currentMinimum, int potentialMinimum, int index) {12 if (potentialMinimum < currentMinimum[index]) {13 currentMinimum[index] = potentialMinimum;14 return true;15 }16 return false;17 }18 19 20 21 22 23 24 25 private int[] hungarian(int[][] costs) {26 final int numLocks = costs.length;27 int[] res = new int[numLocks];28 int[] turnPotentials = new int[numLocks];29 int[] lockPotentials = new int[numLocks + 1];30 int[] lockAssignments = new int[numLocks + 1];31 Arrays.fill(lockAssignments, -1);32 33 for (int currentTurn = 0; currentTurn < numLocks; ++currentTurn) {34 int currentLock = numLocks;35 lockAssignments[currentLock] = currentTurn;36 int[] minReducedCosts = new int[numLocks + 1];37 Arrays.fill(minReducedCosts, Integer.MAX_VALUE);38 int[] previousLockAssignments = new int[numLocks + 1];39 boolean[] locksInOptimalPath = new boolean[numLocks + 1];40 41 while (lockAssignments[currentLock] != -1) {42 locksInOptimalPath[currentLock] = true;43 int assignedTurn = lockAssignments[currentLock];44 int minCostDelta = Integer.MAX_VALUE;45 int nextLock = -1;46 47 for (int lock = 0; lock < numLocks; ++lock)48 if (!locksInOptimalPath[lock]) {49 final int reducedCost =50 costs[assignedTurn][lock] - turnPotentials[assignedTurn] - lockPotentials[lock];51 if (updateMinimum(minReducedCosts, reducedCost, lock))52 previousLockAssignments[lock] = currentLock;53 if (minReducedCosts[lock] < minCostDelta) {54 minCostDelta = minReducedCosts[lock];55 nextLock = lock;56 }57 }58 59 for (int lock = 0; lock <= numLocks; ++lock)60 if (locksInOptimalPath[lock]) {61 turnPotentials[lockAssignments[lock]] += minCostDelta;62 lockPotentials[lock] -= minCostDelta;63 } else {64 minReducedCosts[lock] -= minCostDelta;65 }66 67 currentLock = nextLock;68 }69 70 for (int lock; currentLock != numLocks; currentLock = lock)71 lockAssignments[currentLock] = lockAssignments[lock = previousLockAssignments[currentLock]];72 73 res[currentTurn] = -lockPotentials[numLocks];74 }75 76 return res;77 }78}79