LeetCode: 1561. The maximum number of coins you can get
- Sort from small to large.
- Method 1:
从n/3的位置开始,隔一个取一个
>> The reason for n/3 is to let Bob take the n/3 pile with the least number of coins in all piles - Method 2: Take two for the largest, one for the smallest, and then take the second largest.
/**
* n / 3
* @param piles
* @return
*/
public int maxCoins(int[] piles) {
int ans = 0;
int len = piles.length ;
Arrays.sort(piles);
for (int i = len / 3; i < len; i += 2) {
ans += piles[i];
}
return ans;
}
/**
* 每次将最大的两个取出来,最小的一个取出来。
* ans + 第二大的
* @param piles
* @return
*/
public int maxCoins2(int[] piles) {
int ans = 0;
// 从小到大排序
Arrays.sort(piles);
int len = piles.length - 1;
for (int i = 0, j = len; i + 1 < j ; i++, j -= 2) {
ans += piles[j-1];
}
return ans;
}
public static void main(String[] args) {
int[] n = {
2,4,1,2,7,8};
B b = new B();
System.out.println(b.maxCoins(n));
}