#1753

Maximum Score From Removing Stones

Medium
MathGreedyHeap (Priority Queue)Greedy AlgorithmSorting
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 uses a greedy approach where we always remove stones from the two largest piles. This ensures that we maximize the score by making the most effective moves possible.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the piles to easily access the two largest ones.
  2. 2Step 2: While the two largest piles are non-empty, remove one stone from each and increment the score.
  3. 3Step 3: Return the score when fewer than two piles are left.
solution.py9 lines
1def maxScore(a, b, c):
2    piles = sorted([a, b, c])
3    score = 0
4    while piles[1] > 0:
5        piles[1] -= 1
6        piles[2] -= 1
7        score += 1
8        piles.sort()
9    return score

Complexity note: The time complexity is O(n log n) due to sorting the piles, but since we only have three piles, this is effectively constant time.

  • 1Always prioritize removing stones from the two largest piles to maximize score.
  • 2Sorting helps easily identify the largest piles, but for three piles, it can be done with simple comparisons.

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