Approach
Sorting and greedy selection
For Sell Diminishing-Valued Colored Balls, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 36 lines of Java from the credited upstream file 1648.java.
- The implementation visibly relies on sequence storage.
- 1 loop block detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
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 maxProfit(int[] inventory, int orders) {3 final int MOD = 1_000_000_007;4 long ans = 0;5 long largestCount = 1;6 7 Arrays.sort(inventory);8 9 for (int i = inventory.length - 1; i >= 0; --i, ++largestCount)10 if (i == 0 || inventory[i] > inventory[i - 1]) {11 12 13 final long pick = (i == 0) ? inventory[i] : inventory[i] - inventory[i - 1];14 if (largestCount * pick >= orders) {15 16 17 final long actualPick = orders / largestCount;18 final long remaining = orders % largestCount;19 return (int) ((ans +20 largestCount * trapezoid(inventory[i], inventory[i] - actualPick + 1) +21 remaining * (inventory[i] - actualPick)) %22 MOD);23 }24 ans += largestCount * trapezoid(inventory[i], inventory[i] - pick + 1);25 ans %= MOD;26 orders -= largestCount * pick;27 }28 29 throw new IllegalArgumentException();30 }31 32 private long trapezoid(long a, long b) {33 return (a + b) * (a - b + 1) / 2;34 }35}36