- 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
- 47 lines of Java from the credited upstream file 2528.java.
- The implementation visibly relies on sequence storage.
- 3 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 long maxPower(int[] stations, int r, int k) {3 long left = Arrays.stream(stations).min().getAsInt();4 long right = Arrays.stream(stations).asLongStream().sum() + k + 1;5 6 while (left < right) {7 final long mid = (left + right) / 2;8 if (check(stations.clone(), r, k, mid))9 left = mid + 1;10 else11 right = mid;12 }13 14 return left - 1;15 }16 17 18 boolean check(int[] stations, int r, int additionalStations, long minPower) {19 final int n = stations.length;20 21 long power = 0;22 23 for (int i = 0; i < r; ++i)24 power += stations[i];25 26 for (int i = 0; i < n; ++i) {27 if (i + r < n)28 power += stations[i + r]; 29 if (power < minPower) {30 final long requiredPower = minPower - power;31 32 if (requiredPower > additionalStations)33 return false;34 35 36 stations[Math.min(n - 1, i + r)] += requiredPower;37 additionalStations -= requiredPower;38 power += requiredPower;39 }40 if (i - r >= 0)41 power -= stations[i - r];42 }43 44 return true;45 }46}47