MediumNo. 1561

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

Pattern
Greedy
Topics
Greedy, Array, Math, Game Theory, Sorting
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

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

Complexity

Time
O(n × log n)
Space · auxiliary
O(log n)

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

Related problems
No.ProblemDifficulty
1686Stone Game VIMedium
0910Smallest Range IIMedium
0976Largest Perimeter TriangleEasy
2029Stone Game IXMedium
2195Append K Integers With Minimal SumMedium
2607Make K-Subarray Sums EqualMedium

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 × 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.

Free to download. Check it runs on your machine, then pick a plan.