Skip to content

LeetCode: 1561-Maximum Number of Coins You Can Get 解題紀錄

Last Updated on 2023-11-24 by Clay

題目

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 the 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 that 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

Constraints:

  • 3 <= piles.length <= 105
  • piles.length % 3 == 0
  • 1 <= piles[i] <= 104

解題思路

這個題目乍看之下似乎很複雜,但想清楚大家拿硬幣的順序是固定的,就可以用貪婪演算法直接計算我們所能拿到的硬幣最大數量。

由於我們一定是第二位拿的,所以可以想像成每一輪我們都固定拿第二大的硬幣堆,而最後選的一定要給他最小的硬幣堆 —— 所以我們所能拿的最大值,就是每一輪都組成 (當前最大硬幣堆, 當前第二大硬幣堆, 當前最小硬幣堆) 這樣的硬幣堆選取。

以 Example 1 為例:[2,4,1,2,7,8] 我們會先重排成 [1, 2, 2, 4, 7, 8],接著第一輪我們會選擇 (1, 7, 8) 的組合,我們第二位挑選所以只能挑 7;而第二輪我們只能選剩下的 (2, 2, 4),我們只能拿 2,所以答案是 7 + 2 = 9 —— 就是我們能拿到的最多硬幣數量組合。


C++ 範例程式碼

class Solution {
public:
    int maxCoins(vector<int>& piles) {
        // Init
        int coins = 0;
        int left = 0;
        int right = piles.size() - 1;
        
        // Sort
        sort(piles.begin(), piles.end());

        // Count
        while (left < right - 1) {
            coins += piles[right-1];
            ++left;
            right -= 2;
        }

        return coins;
    }
};




Python 範例程式碼

class Solution:
    def maxCoins(self, piles: List[int]) -> int:
        # Init
        coins = 0
        left = 0
        right = len(piles) - 1

        # Sort
        piles = sorted(piles)

        # Count
        while left < right - 1:
            coins += piles[right - 1]

            right -= 2
            left += 1

        return coins

References


Read More

Leave a Reply