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
- 41 lines of C++ from the credited upstream file 1648.cpp.
- 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:3 int maxProfit(vector<int>& inventory, int orders) {4 constexpr int kMod = 1'000'000'007;5 long ans = 0;6 long largestCount = 1;7 8 ranges::sort(inventory, greater<>());9 10 for (int i = 0; i < inventory.size(); ++i, ++largestCount)11 if (i == inventory.size() - 1 || inventory[i] > inventory[i + 1]) {12 13 14 const int pick = (i == inventory.size() - 1)15 ? inventory[i]16 : inventory[i] - inventory[i + 1];17 if (largestCount * pick >= orders) {18 19 20 const int actualPick = orders / largestCount;21 const int remaining = orders % largestCount;22 return (ans +23 largestCount *24 trapezoid(inventory[i], inventory[i] - actualPick + 1) +25 static_cast<long>(remaining) * (inventory[i] - actualPick)) %26 kMod;27 }28 ans += largestCount * trapezoid(inventory[i], inventory[i] - pick + 1);29 ans %= kMod;30 orders -= largestCount * pick;31 }32 33 throw;34 }35 36 private:37 long trapezoid(long a, long b) {38 return (a + b) * (a - b + 1) / 2;39 }40};41