Maximum Number of Coins You Can Get - Problem

There are 3n piles of coins of varying size. You and your friends Alice and Bob will take piles of coins following this process:

  1. In each step, you choose any 3 piles of coins (not necessarily consecutive)
  2. Alice picks the pile with the maximum number of coins
  3. You pick the pile with the next maximum number of coins
  4. Bob picks the remaining pile
  5. Repeat until no piles remain

Given an array piles where piles[i] is the number of coins in the ith pile, return the maximum number of coins you can collect.

Input & Output

Example 1 — Basic Game
$ Input: piles = [2,4,1,2,7,8]
Output: 9
💡 Note: Sort: [8,7,4,2,2,1]. Take positions 2,3: piles[2]=4, piles[3]=2. Total: 4+2=6. Wait, let me recalculate: n=2, take indices 2 to 3, which gives 4+2=6. But optimal is: Alice gets 8,7 and you get 4,2, Bob gets 2,1. Actually, you get 7+2=9.
Example 2 — Larger Array
$ Input: piles = [9,8,7,6,5,1]
Output: 14
💡 Note: Sort: [9,8,7,6,5,1]. Take every second position starting from 1: piles[1]=8, piles[3]=6. Total: 8+6=14
Example 3 — Equal Values
$ Input: piles = [1,1,1,1,1,1]
Output: 2
💡 Note: All piles equal, sort doesn't change order. Take every second position starting from 1: piles[1]=1, piles[3]=1. Total: 1+1=2

Constraints

  • 3 ≤ piles.length ≤ 105
  • piles.length % 3 == 0
  • 1 ≤ piles[i] ≤ 104

Visualization

Tap to expand
Maximum Number of Coins You Can Get INPUT piles = [2, 4, 1, 2, 7, 8] 2 4 1 2 7 8 Alice (Max) You (2nd Max) Bob (Min) ALGORITHM STEPS 1 Sort Descending [8, 7, 4, 2, 2, 1] 2 Group into triplets Pick 3 at a time 3 Assign piles Alice=Max, You=2nd, Bob=Min 4 Sum your picks Collect 2nd largest each round Round 1: 8 7 4 Round 2: 2 2 1 You get: 7 + 2 = 9 FINAL RESULT Your Collection 7 coins 2 coins Output: 9 OK - Maximum coins collected! Alice total: 8 + 2 = 10 You total: 7 + 2 = 9 Bob total: 4 + 1 = 5 Key Insight: By sorting in descending order, we ensure Alice always gets the maximum pile. To maximize your coins, always pick the 2nd largest from each triplet. Give Bob the smallest piles by pairing them with the largest. Strategy: You always get elements at indices 1, 3, 5... (every 2nd from sorted array, n times) TutorialsPoint - Maximum Number of Coins You Can Get | Greedy Strategy (Sort First)
Asked in
Facebook 15 Google 12 Amazon 8
23.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen