Maximum Number of Coins You Can Get

medium array math greedy sorting game theory

Problem

There are 3n piles of coins. In each turn: Alice picks the largest pile, you pick the next-largest, Bob picks the smallest. Repeat n turns; return the maximum coins YOU can collect.

Inputpiles=[2,4,1,2,7,8]
Output9
Sorted desc: 8,7,4,2,2,1 → you take 7 and 2 = 9.

def max_coins(piles):
    a = sorted(piles)
    n = len(a) // 3
    return sum(a[-2 - 2*i] for i in range(n))
function maxCoins(piles) {
  const a = piles.slice().sort((x, y) => x - y);
  const n = a.length / 3;
  let ans = 0;
  for (let i = 0; i < n; i++) ans += a[a.length - 2 - 2 * i];
  return ans;
}
class Solution {
    public int maxCoins(int[] piles) {
        Arrays.sort(piles);
        int n = piles.length / 3, ans = 0;
        for (int i = 0; i < n; i++) ans += piles[piles.length - 2 - 2 * i];
        return ans;
    }
}
int maxCoins(vector& piles) {
    sort(piles.begin(), piles.end());
    int n = piles.size() / 3, ans = 0;
    for (int i = 0; i < n; i++) ans += piles[piles.size() - 2 - 2 * i];
    return ans;
}
Time: O(n log n) Space: O(1)