Input: piles =[2,4,1,2,7,8]Output: 9Explanation: Choose the triplet(2,7,8), Alice Pick the pile with8 coins, you the pile with**7** coins and Bob the last one.Choose the triplet(1,2,4), Alice Pick the pile with4 coins, you the pile with**2** coins and Bob the last one.The maximum number of coins which you can have are:7+2=9.On the other hand if we choose thisarrangement(1,**2**,8),(2,**4**,7) you only get 2+4=6 coins which is not optimal.
To maximize your coins, always let Alice take the largest, you take the second largest, and Bob takes the smallest from each group of 3. By sorting the piles and picking in this order, you maximize your total.
classSolution {
public:int maxCoins(vector<int>& piles) {
sort(piles.begin(), piles.end());
int n = piles.size() /3, ans =0, j = piles.size() -2;
for (int i =0; i < n; ++i, j -=2) ans += piles[j];
return ans;
}
};
1
2
3
4
5
6
7
8
9
import"sort"funcmaxCoins(piles []int) int {
sort.Ints(piles)
n, ans, j:= len(piles)/3, 0, len(piles)-2fori:=0; i < n; i, j = i+1, j-2 {
ans+=piles[j]
}
returnans}
1
2
3
4
5
6
7
8
9
import java.util.*;
classSolution {
publicintmaxCoins(int[] piles) {
Arrays.sort(piles);
int n = piles.length/ 3, ans = 0, j = piles.length- 2;
for (int i = 0; i < n; i++, j -= 2) ans += piles[j];
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funmaxCoins(piles: IntArray): Int {
piles.sort()
var ans = 0var j = piles.size - 2 repeat(piles.size / 3) {
ans += piles[j]
j -=2 }
return ans
}
}
1
2
3
4
5
6
7
8
9
classSolution:
defmaxCoins(self, piles: list[int]) -> int:
piles.sort()
ans =0 j = len(piles) -2for _ in range(len(piles)//3):
ans += piles[j]
j -=2return ans
1
2
3
4
5
6
7
8
9
10
11
12
impl Solution {
pubfnmax_coins(mut piles: Vec<i32>) -> i32 {
piles.sort();
letmut ans =0;
letmut j = piles.len() -2;
for _ in0..(piles.len()/3) {
ans += piles[j];
j -=2;
}
ans
}
}