[LeetCode] 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.

Example 1:
Input: piles = [2,4,1,2,7,8]
Output: 9
Explanation: Choose the triplet (2, 7, 8), Alice Pick the pile with 8 coins, you the pile with 7 coins and Bob the last one.
Choose the triplet (1, 2, 4), Alice Pick the pile with 4 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 this arrangement (1, 2, 8), (2, 4, 7) you only get 2 + 4 = 6 coins which is not optimal.

Example 2:
Input: piles = [2,4,5]
Output: 4

Example 3:
Input: piles = [9,8,7,6,5,1,2,3,4]
Output: 18

你可以获得的最大硬币数目。

有 3n 堆数目不一的硬币,你和你的朋友们打算按以下方式分硬币:
每一轮中,你将会选出 任意 3 堆硬币(不一定连续)。
Alice 将会取走硬币数量最多的那一堆。
你将会取走硬币数量第二多的那一堆。
Bob 将会取走最后一堆。
重复这个过程,直到没有更多硬币。
给你一个整数数组 piles ,其中 piles[i] 是第 i 堆中硬币的数目。
返回你可以获得的最大硬币数目。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-number-of-coins-you-can-get
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

思路是排序 + two pointer。这道题我们必须排序,否则是拿不到次多的那一堆的。排序完之后,我们用左右两个指针逼近中间,左指针 i 指向的是每次选取的三堆硬币中最少的,右指针 j 指向的是每次选取的三堆硬币中最多的,j - 1 指向的是次多的。要选取的次数是piles.length / 3。

复杂度

时间O(nlogn)
空间O(1)

代码

Java实现

class Solution {
    public int maxCoins(int[] piles) {
        Arrays.sort(piles);
        int n = piles.length;
        int i = 0;
        int j = n - 1;
        int res = 0;
        int count = n / 3;
        while (i < j && count != 0) {
            if (i < j - 1) {
                res += piles[j - 1];
                count--;
            }
            i++;
            j -= 2;
        }
        return res;
    }
}
posted @ 2021-02-25 01:05  CNoodle  阅读(178)  评论(0编辑  收藏  举报