#1561
Maximum Number of Coins You Can Get
MediumArrayMathGreedySortingGame TheoryGreedySorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
In the optimal approach, we sort the piles and strategically select piles to maximize our coins while minimizing what Bob gets. By always allowing Bob to take the smallest pile, we can ensure we get the maximum possible coins.
⚙️
Algorithm
3 steps- 1Step 1: Sort the piles in ascending order.
- 2Step 2: Select the last n piles for yourself, skipping every third pile from the end (which Bob will take).
- 3Step 3: Sum the coins from the selected piles to get the maximum coins you can collect.
solution.py5 lines
1# Full working Python code
2
3def maxCoins(piles):
4 piles.sort()
5 return sum(piles[len(piles)//3:len(piles)//3*2:2])ℹ
Complexity note: The complexity is O(n log n) due to the sorting step, which is efficient for large inputs compared to the brute force approach.
- 1You can maximize your coins by allowing Bob to take the smallest pile.
- 2Sorting the piles helps in easily selecting the optimal coins.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.