Maximum number of coins you can get

November 26, 2022

greedy queue

Problem URL: Maximum number of coins you can get

We will use a double ended queue to store the piles. We will sort the piles in descending order. We will iterate over the piles. We will pop the first and the last element from the queue. We will add the popped elements to the result. We will return the result.

class Solution:
    def maxCoins(self, piles: List[int]) -> int:
        piles = collections.deque(sorted(piles))
        res = 0
        while piles:
            piles.pop()         # Alice
            res += piles.pop()  # Me
            piles.popleft()     # Bob
        return res

Time complexity: O(nlog(n)), n is the length of piles
Space complexity: O(n)