Maximum Number of Coins You Can Get — LeetCode 1561 Python Solution

MediumGreedyArrayMathGame TheorySorting
Problem
#1561
Pattern
Greedy
Reading time
2 min

The problem

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 3 piles of coins (not necessarily consecutive). Of your choice, Alice will pick the pile with the maximum number of coins.

Example

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.

Python solution

Python
class Solution:
    def maxCoins(self, piles: List[int]) -> int:
        piles.sort()
        return sum(piles[len(piles) // 3 :][::2])

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(\log n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 1561. Maximum Number of Coins You Can Get is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1561. Maximum Number of Coins You Can Get?
LeetCode 1561. Maximum Number of Coins You Can Get is rated Medium on LeetCode.
What is the time complexity of LeetCode 1561. Maximum Number of Coins You Can Get?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 1561. Maximum Number of Coins You Can Get?
The Python solution on this page uses O(\log n) auxiliary space.
What topics does LeetCode 1561. Maximum Number of Coins You Can Get cover?
LeetCode 1561. Maximum Number of Coins You Can Get is tagged Greedy, Array, Math, Game Theory and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview