Maximum Score From Removing Stones — Medium Problem & Solution
Three piles hold a, b and c stones. On each turn you pick two different non-empty piles and remove one stone from each, scoring one point.
- Difficulty: Medium
- Topics: Math, Greedy, Heap
- Asked at: Amazon, Google, Zoho
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Three piles hold a, b and c stones. On each turn you pick two different non-empty piles and remove one stone from each, scoring one point.
Play until fewer than two piles are non-empty. Return the maximum score you can reach.
Example 1
Input: a = 2, b = 4, c = 6
Output: 6
Explanation: The two smaller piles together match the biggest, so every stone can be paired off.
Example 2
Input: a = 4, b = 4, c = 6
Output: 7
Explanation: Fourteen stones, so seven pairs.
Example 3
Input: a = 1, b = 8, c = 8
Output: 8
Explanation: The two 8-piles carry the game; one stone is stranded.
Constraints
1 <= a, b, c <= 10^5
How to solve Maximum Score From Removing Stones
Two cases. If the biggest pile exceeds the sum of the other two, every turn must use it, so the score is that sum. Otherwise the piles can be balanced and the score is ⌊(a + b + c) / 2⌋.
Approach
- Let
mxbe the largest pile andrestthe sum of the other two. - If
rest < mx, returnrest. - Otherwise return
(a + b + c) / 2, rounded down.
Why it works
The first case is a hard ceiling: every turn consumes one stone from a pile other than the biggest, so the other two piles run out after rest turns. In the second case no pile can ever outgrow the rest, so a stone is stranded only when the total is odd — hence the floor. Simulating with a heap (always take from the two largest piles) reaches the same answer, more slowly.
Complexity
- Time —
O(1) - Space —
O(1)
Pitfalls
- Always answering
(a + b + c) / 2overshoots when one pile dominates. - Always answering
restundershoots a balanced set of piles. - The division rounds down; an odd total strands one stone.
Reference solution
Python
def maximumScore(a: int, b: int, c: int) -> int:
total = a + b + c
mx = max(a, b, c)
rest = total - mx
return rest if rest < mx else total // 2JavaScript
var maximumScore = function(a, b, c) {
var total = a + b + c;
var mx = Math.max(a, Math.max(b, c));
var rest = total - mx;
return rest < mx ? rest : Math.floor(total / 2);
};Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.