Given three piles of stones, represented by the integers a
, b
, and c
, you can perform the following operation any number of times:
0 ≤ a, b, c ≤ 10^5
At first, one might consider simulating the process: repeatedly picking the two largest non-empty piles and removing one stone from each, counting each operation. However, this brute-force approach would be inefficient for large input sizes.
To optimize, we need to recognize that the only thing that matters is the number of stones in each pile and the rule that you can only remove stones from two different non-empty piles at a time. The operation is not dependent on the order, but on the counts.
The main insight is that the process should continue until one or two piles become empty. The maximum number of operations is limited by both the total number of stones and the largest pile: you can't make more moves than half the total number of stones (since each move removes two stones), and you can't continue once the largest pile is depleted by the other two.
Let's break down the algorithm step-by-step:
x
, y
, z
such that x ≤ y ≤ z
.
z
) has more stones than the sum of the other two (x + y
), then the maximum number of moves is x + y
. This is because after x + y
moves, the two smaller piles will be empty, and no more moves can be made.
(x + y + z) // 2
. This is because each move removes two stones, and you can't remove more stones than are present.
total = a + b + c
.max_pile = max(a, b, c)
.min(total // 2, total - max_pile)
as the answer.
Example Input: a = 2
, b = 4
, c = 6
Step-by-step:
2, 4, 6
(already sorted)2 + 4 + 6 = 12
6
6 > 2 + 4
? No (6 = 6
), so use total // 2 = 6
6
Brute-force Approach:
O(a + b + c)
iterations.O(1)
for three piles, but still inefficient for large pile sizes.O(1)
time complexity.O(1)
as no extra space is used.
The key insight for this problem is realizing that the maximum number of moves is constrained by both the total number of stones and the size of the largest pile. By using the formula min((a + b + c) // 2, a + b + c - max(a, b, c))
, we can compute the answer in constant time. This makes the solution both elegant and highly efficient, avoiding unnecessary simulation or iteration.
class Solution:
def maximumScore(self, a: int, b: int, c: int) -> int:
total = a + b + c
max_pile = max(a, b, c)
return min(total // 2, total - max_pile)
class Solution {
public:
int maximumScore(int a, int b, int c) {
int total = a + b + c;
int max_pile = std::max({a, b, c});
return std::min(total / 2, total - max_pile);
}
};
class Solution {
public int maximumScore(int a, int b, int c) {
int total = a + b + c;
int max_pile = Math.max(a, Math.max(b, c));
return Math.min(total / 2, total - max_pile);
}
}
var maximumScore = function(a, b, c) {
const total = a + b + c;
const max_pile = Math.max(a, b, c);
return Math.min(Math.floor(total / 2), total - max_pile);
};