class Solution:
def maxCoins(self, piles):
piles.sort()
n = len(piles) // 3
res = 0
# Start from the second largest in each group of 3
for i in range(n, len(piles), 2):
res += piles[i]
return res
class Solution {
public:
int maxCoins(vector<int>& piles) {
sort(piles.begin(), piles.end());
int n = piles.size() / 3;
int res = 0;
for (int i = n; i < piles.size(); i += 2) {
res += piles[i];
}
return res;
}
};
import java.util.*;
class Solution {
public int maxCoins(int[] piles) {
Arrays.sort(piles);
int n = piles.length / 3;
int res = 0;
for (int i = n; i < piles.length; i += 2) {
res += piles[i];
}
return res;
}
}
var maxCoins = function(piles) {
piles.sort((a, b) => a - b);
let n = Math.floor(piles.length / 3);
let res = 0;
for (let i = n; i < piles.length; i += 2) {
res += piles[i];
}
return res;
};
piles of 3n integers, representing piles of coins. You are playing a game with two friends (Alice and Bob). Each round, all three of you take turns choosing one pile each:
piles in ascending order makes it easy to pick the largest, second largest, and smallest in each round.3n piles, we can think of the sorted array as n groups of three piles each.nth element and skipping every other pile (because Alice gets the largest, you the next, Bob the smallest, and so on).piles = [2,4,1,2,7,8]
[1,2,2,4,7,8]
n=2):
2 + 7 = 9 coins.
piles.O(n log n) because sorting the array dominates the runtime. The subsequent loop is O(n).O(1) extra space (if sorting in-place), or O(n) if sorting creates a new array.