#3207

Maximum Points After Enemy Battles

Medium
ArrayGreedyGreedySortingArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

The optimal solution leverages a greedy approach by first sorting the enemies based on their energy values. We prioritize battling weaker enemies to gain points and then use those points to battle stronger enemies.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the enemyEnergies array in ascending order.
  2. 2Step 2: Initialize points to 0 and iterate through the sorted array.
  3. 3Step 3: For each enemy, if currentEnergy is sufficient, battle them to gain points, otherwise, if points are available, mark them to regain energy.
solution.py13 lines
1# Full working Python code
2
3def maxPointsOptimal(enemyEnergies, currentEnergy):
4    enemyEnergies.sort()
5    points = 0
6    for energy in enemyEnergies:
7        if currentEnergy >= energy:
8            points += 1
9            currentEnergy -= energy
10        elif points > 0:
11            currentEnergy += energy
12            points -= 1
13    return points

Complexity note: The sorting step takes O(n log n), and the single pass through the array takes O(n), making this approach efficient overall.

  • 1Greedy strategies often yield optimal solutions in problems involving choices and resources.
  • 2Sorting can simplify decision-making by allowing us to handle the smallest elements first.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.