Maximum Number of Coins You Can Get — LeetCode 1561 Python Solution
- Problem
- #1561
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
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
class Solution:
def maxCoins(self, piles: List[int]) -> int:
piles.sort()
return sum(piles[len(piles) // 3 :][::2])Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(\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.