- 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
- 50 lines of Java from the credited upstream file 2604.java.
- The implementation visibly relies on sequence storage.
- 2 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 minimumTime(int[] hens, int[] grains) {3 Arrays.sort(hens);4 Arrays.sort(grains);5 6 final int maxPosition = Math.max(Arrays.stream(hens).max().getAsInt(), 7 Arrays.stream(grains).max().getAsInt());8 final int minPosition = Math.min(Arrays.stream(hens).min().getAsInt(), 9 Arrays.stream(grains).min().getAsInt());10 int l = 0;11 int r = (int) (1.5 * (maxPosition - minPosition));12 13 while (l < r) {14 final int m = (int) ((l + (long) r) / 2);15 if (canEat(hens, grains, m))16 r = m;17 else18 l = m + 1;19 }20 21 return (int) l;22 }23 24 25 private boolean canEat(int[] hens, int[] grains, int time) {26 int i = 0; 27 for (final int hen : hens) {28 int rightMoves = time;29 if (grains[i] < hen) {30 31 final int leftMoves = hen - grains[i];32 if (leftMoves > time)33 return false;34 final int leftThenRight = time - 2 * leftMoves;35 final int rightThenLeft = (time - leftMoves) / 2;36 rightMoves = Math.max(0, Math.max(leftThenRight, rightThenLeft));37 }38 i = firstGreater(grains, hen + rightMoves);39 if (i == grains.length)40 return true;41 }42 return false;43 }44 45 private int firstGreater(int[] arr, int target) {46 final int i = Arrays.binarySearch(arr, target + 1);47 return i < 0 ? -i - 1 : i;48 }49}50