You are playing a solitaire game with **three piles** of stones of sizes `a`

, `b`

, and `c`

respectively. Each turn you choose two **different non-empty **piles, take one stone from each, and add `1`

point to your score. The game stops when there are **fewer than two non-empty** piles (meaning there are no more available moves).

Given three integers `a`

, `b`

, and `c`

, return *the* *maximum* **score** you can get.

**Example 1:**

Input:a = 2, b = 4, c = 6Output:6Explanation:The starting state is (2, 4, 6). One optimal set of moves is: - Take from 1st and 3rd piles, state is now (1, 4, 5) - Take from 1st and 3rd piles, state is now (0, 4, 4) - Take from 2nd and 3rd piles, state is now (0, 3, 3) - Take from 2nd and 3rd piles, state is now (0, 2, 2) - Take from 2nd and 3rd piles, state is now (0, 1, 1) - Take from 2nd and 3rd piles, state is now (0, 0, 0) There are fewer than two non-empty piles, so the game ends. Total: 6 points.

**Example 2:**

Input:a = 4, b = 4, c = 6Output:7Explanation:The starting state is (4, 4, 6). One optimal set of moves is: - Take from 1st and 2nd piles, state is now (3, 3, 6) - Take from 1st and 3rd piles, state is now (2, 3, 5) - Take from 1st and 3rd piles, state is now (1, 3, 4) - Take from 1st and 3rd piles, state is now (0, 3, 3) - Take from 2nd and 3rd piles, state is now (0, 2, 2) - Take from 2nd and 3rd piles, state is now (0, 1, 1) - Take from 2nd and 3rd piles, state is now (0, 0, 0) There are fewer than two non-empty piles, so the game ends. Total: 7 points.

**Example 3:**

Input:a = 1, b = 8, c = 8Output:8Explanation:One optimal set of moves is to take from the 2nd and 3rd piles for 8 turns until they are empty. After that, there are fewer than two non-empty piles, so the game ends.

**Constraints:**

`1 <= a, b, c <= 10`

^{5}

**Solution 1: Greedy**

Take two stones (one each) from the largest two piles, until one is empty.

Time complexity: O(n)

Space complexity: O(1)

## C++

1 2 3 4 5 6 7 8 9 10 11 12 13 |
class Solution { public: int maximumScore(int a, int b, int c) { array<int, 3> s{a,b,c}; sort(begin(s), end(s)); int ans = 0; while (s[1]-- && s[2]--) { ++ans; sort(begin(s), end(s)); } return ans; } }; |

**Solution 2: Math**

First, let’s assuming a <= b <= c.

There are two conditions:

1. a + b <= c, we can pair c with a first and then b. Total pairs is (a + b + (a + b)) / 2

2. a + b > c, we can pair c with a, b “evenly”, and then pair a with b, total pairs is (a + b + c) / 2

ans = (a + b + min(a + b, c)) / 2

Time complexity: O(1)

Space complexity: O(1)

## C++

1 2 3 4 5 6 7 8 |
class Solution { public: int maximumScore(int a, int b, int c) { array<int, 3> s{a,b,c}; sort(begin(s), end(s)); return (s[0] + s[1] + min(s[0] + s[1], s[2])) / 2; } }; |

请尊重作者的劳动成果，转载请注明出处！花花保留对文章／视频的所有权利。

如果您喜欢这篇文章／视频，欢迎您捐赠花花。

If you like my articles / videos, donations are welcome.

## Be First to Comment