Maximum Number of Coins You Can Get Problem
Description
LeetCode Problem 1561.
There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows:
- In each step, you will choose any
3piles of coins (not necessarily consecutive). - Of your choice, Alice will pick the pile with the maximum number of coins.
- You will pick the next pile with the maximum number of coins.
- Your friend Bob will pick the last pile.
- Repeat until there are no more piles of coins.
Given an array of integers piles where piles[i] is the number of coins in the i^th pile.
Return the maximum number of coins that you can have.
Example 1:
Input: piles = [2,4,1,2,7,8]
Output: 9
Explanation: Choose the triplet (2, 7, 8), Alice Pick the pile with 8 coins, you the pile with 7 coins and Bob the last one.
Choose the triplet (1, 2, 4), Alice Pick the pile with 4 coins, you the pile with 2 coins and Bob the last one.
The maximum number of coins which you can have are: 7 + 2 = 9.
On the other hand if we choose this arrangement (1, 2, 8), (2, 4, 7) you only get 2 + 4 = 6 coins which is not optimal.
Example 2:
Input: piles = [2,4,5]
Output: 4
Example 3:
Input: piles = [9,8,7,6,5,1,2,3,4]
Output: 18
Constraints:
3 <= piles.length <= 10^5piles.length % 3 == 01 <= piles[i] <= 10^4
Solution
Approach: Greedy After Sorting
In every triplet, Alice takes the largest pile, you take the middle one and Bob takes the smallest. To get as much as possible, give Bob the smallest piles and make your pile as close to Alice's as possible.
Sort the piles. Bob takes n piles in total (there are 3n piles), so let him have the n smallest ones. Of the remaining 2n piles, form triplets from the top: the two largest piles go with one of Bob's small piles, so Alice gets the largest and you get the second largest; then the next two largest, and so on. You end up with every second pile counting down from the second largest, i.e. the piles at indexes n, n + 2, n + 4, ..., 3n - 2 of the sorted array.
Why it is optimal: in each triplet, your pile is beaten by Alice's, so at best you can get the 2nd, 4th, 6th, ... largest piles overall, and this choice achieves exactly that.
Complexity: O(n log n) time for sorting and O(n) extra space for the sorted copy (O(log n) if sorting in place).
class Solution:
def maxCoins(self, piles: List[int]) -> int:
piles = sorted(piles)
# Bob takes the n smallest piles; from the rest, pair them up from the top: Alice gets the larger, you the next.
n = len(piles) // 3
return sum(piles[i] for i in range(n, len(piles), 2))