Approach
Sorting and greedy selection
For Minimum Amount of Damage Dealt to Bob, 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 C++ from the credited upstream file 3273.cpp.
- The implementation visibly relies on sequence storage.
- 2 loop blocks 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.
1struct Enemy {2 int damage;3 int timeTakenDown;4};5 6class Solution {7 public:8 long long minDamage(int power, vector<int>& damage, vector<int>& health) {9 long ans = 0;10 long sumDamage = accumulate(damage.begin(), damage.end(), 0L);11 vector<Enemy> enemies;12 13 for (int i = 0; i < damage.size(); ++i)14 enemies.emplace_back(damage[i], (health[i] + power - 1) / power);15 16 17 18 19 20 21 22 23 24 ranges::sort(enemies, ranges::greater{}, [](const Enemy& e) {25 return static_cast<double>(e.damage) / e.timeTakenDown;26 });27 28 for (const Enemy& enemy : enemies) {29 ans += sumDamage * enemy.timeTakenDown;30 sumDamage -= enemy.damage;31 }32 33 return ans;34 }35};36