- 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 2234.java.
- The implementation visibly relies on sequence storage.
- 4 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 maximumBeauty(int[] flowers, long newFlowers, int target, int full, int partial) {3 final int n = flowers.length;4 5 6 for (int i = 0; i < n; ++i)7 flowers[i] = Math.min(flowers[i], target);8 Arrays.sort(flowers);9 10 11 if (flowers[0] == target)12 return (long) n * full;13 14 15 if (newFlowers >= (long) n * target - Arrays.stream(flowers).asLongStream().sum())16 return Math.max((long) n * full, (n - 1L) * full + (target - 1L) * partial);17 18 long ans = 0;19 long leftFlowers = newFlowers;20 21 long[] cost = new long[flowers.length];22 23 for (int i = 1; i < flowers.length; ++i)24 25 cost[i] = cost[i - 1] + i * (flowers[i] - flowers[i - 1]);26 27 int i = flowers.length - 1; 28 while (flowers[i] == target)29 --i;30 31 for (; leftFlowers >= 0; --i) {32 33 34 35 36 final int j = firstGreater(cost, i, leftFlowers);37 final long minIncomplete = flowers[j - 1] + (leftFlowers - cost[j - 1]) / j;38 ans = Math.max(ans, (n - 1L - i) * full + (long) minIncomplete * partial);39 leftFlowers -= Math.max(0, target - flowers[i]);40 }41 42 return ans;43 }44 45 private int firstGreater(long[] A, int maxIndex, long target) {46 final int i = Arrays.binarySearch(A, 0, maxIndex + 1, target + 1);47 return i < 0 ? -i - 1 : i;48 }49}50