LeetCode 题解工作台

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

有 3n 堆数目不一的硬币,你和你的朋友们打算按以下方式分硬币: 每一轮中,你将会选出 任意 3 堆硬币(不一定连续)。 Alice 将会取走硬币数量最多的那一堆。 你将会取走硬币数量第二多的那一堆。 Bob 将会取走最后一堆。 重复这个过程,直到没有更多硬币。 给你一个整数数组 piles ,其中…

category

5

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 贪心·invariant

bolt

答案摘要

为了让我们获得的硬币数量最多,我们可以贪心地让 Bob 拿走最少的 堆硬币。我们每次先让 Alice 拿走最多的一堆硬币,然后让我们拿走第二多的一堆硬币,依次循环,直到没有硬币可拿。 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 是硬币堆数。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

有 3n 堆数目不一的硬币,你和你的朋友们打算按以下方式分硬币:

  • 每一轮中,你将会选出 任意 3 堆硬币(不一定连续)。
  • Alice 将会取走硬币数量最多的那一堆。
  • 你将会取走硬币数量第二多的那一堆。
  • Bob 将会取走最后一堆。
  • 重复这个过程,直到没有更多硬币。

给你一个整数数组 piles ,其中 piles[i] 是第 i 堆中硬币的数目。

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

 

示例 1:

输入:piles = [2,4,1,2,7,8]
输出:9
解释:选出 (2, 7, 8) ,Alice 取走 8 枚硬币的那堆,你取走 7 枚硬币的那堆,Bob 取走最后一堆。
选出 (1, 2, 4) , Alice 取走 4 枚硬币的那堆,你取走 2 枚硬币的那堆,Bob 取走最后一堆。
你可以获得的最大硬币数目:7 + 2 = 9.
考虑另外一种情况,如果选出的是 (1, 2, 8) 和 (2, 4, 7) ,你就只能得到 2 + 4 = 6 枚硬币,这不是最优解。

示例 2:

输入:piles = [2,4,5]
输出:4

示例 3:

输入:piles = [9,8,7,6,5,1,2,3,4]
输出:18

 

提示:

  • 3 <= piles.length <= 10^5
  • piles.length % 3 == 0
  • 1 <= piles[i] <= 10^4
lightbulb

解题思路

方法一:贪心 + 排序

为了让我们获得的硬币数量最多,我们可以贪心地让 Bob 拿走最少的 nn 堆硬币。我们每次先让 Alice 拿走最多的一堆硬币,然后让我们拿走第二多的一堆硬币,依次循环,直到没有硬币可拿。

时间复杂度 O(n×logn)O(n \times \log n),空间复杂度 O(logn)O(\log n)。其中 nn 是硬币堆数。

1
2
3
4
5
class Solution:
    def maxCoins(self, piles: List[int]) -> int:
        piles.sort()
        return sum(piles[len(piles) // 3 :][::2])
speed

复杂度分析

指标
时间O(n \cdot \log{}n)
空间O(\log n)
psychology

面试官常问的追问

外企场景
  • question_mark

    Check if you can always take the second largest pile instead of recomputing each triplet.

  • question_mark

    Watch how the invariant of Alice > you > Bob guides greedy selection.

  • question_mark

    Consider array length divisibility by three as part of your selection logic.

warning

常见陷阱

外企场景
  • error

    Picking the largest pile for yourself instead of the second largest reduces the maximum coins.

  • error

    Failing to sort the array before selecting can lead to suboptimal totals.

  • error

    Mismanaging the iteration and including Bob's pile in your sum breaks the greedy invariant.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Maximizing coins when only two players pick in order with the same greedy pattern.

  • arrow_right_alt

    Extending to n players where each must pick in descending priority while maintaining fairness.

  • arrow_right_alt

    Choosing from piles that are not multiples of three and adjusting the greedy selection accordingly.

help

常见问题

外企场景

你可以获得的最大硬币数目题解:贪心·invariant | LeetCode #1561 中等