Skip to content

1561. Maximum Number of Coins You Can Get 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(\texttt{sort})$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  int maxCoins(vector<int>& piles) {
    ranges::sort(piles);

    int ans = 0;

    // piles = [S S M L M L], pick all the M.
    for (int i = piles.size() / 3; i < piles.size(); i += 2)
      ans += piles[i];

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public int maxCoins(int[] piles) {
    Arrays.sort(piles);

    int ans = 0;

    // piles = [S S M L M L], pick all the M.
    for (int i = piles.length / 3; i < piles.length; i += 2)
      ans += piles[i];

    return ans;
  }
}
1
2
3
class Solution:
  def maxCoins(self, piles: list[int]) -> int:
    return sum(sorted(piles)[len(piles) // 3::2])