刷题笔记
1561. Maximum Number of Coins You Can Get
题目
There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows:
In each step, you will choose any 3 piles of coins (not necessarily consecutive).
Of your choice, Alice will pick the pile with the maximum number of coins.
You will pick the next pile with maximum number of coins.
Your friend Bob will pick the last pile.
Repeat until there are no more piles of coins.
Given an array of integers piles where piles[i] is the number of coins in the ith pile.
Return the maximum number of coins which you can have.
思路
- 首先总结题目规律,自己要拿的那一份一定要是每一组的中间那份。
- 那么要最大化总量,就要把数组排序,每次的三份都是两个最大的加一个最小的。
- 思路理清楚了实现就很简单了。
代码实现
class Solution {
public int maxCoins(int[] piles) {
Arrays.sort(piles);
int n = piles.length, sum = 0;
for (int i = n / 3; i < n; i += 2) {
sum += piles[i];
}
return sum;
}
}