LeetCode 题解工作台

幸福值最大化的选择方案

给你一个长度为 n 的数组 happiness ,以及一个 正整数 k 。 n 个孩子站成一队,其中第 i 个孩子的 幸福值 是 happiness[i] 。你计划组织 k 轮筛选从这 n 个孩子中选出 k 个孩子。 在每一轮选择一个孩子时,所有 尚未 被选中的孩子的 幸福值 将减少 1 。注意,幸…

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 贪心·invariant

bolt

答案摘要

为了使得幸福值之和尽可能大,我们应该优先选择幸福值大的孩子。因此,我们可以对孩子按照幸福值从大到小排序,然后依次选择 个孩子。对于当前第 个孩子,能够得到的幸福值为 $\max(\textit{happiness}[i] - i, 0)$,最后返回这 个孩子的幸福值之和。 时间复杂度 $O(n \times \log n + k)$,空间复杂度 $O(\log n)$。其中 是数组 的长…

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个长度为 n 的数组 happiness ,以及一个 正整数 k

n 个孩子站成一队,其中第 i 个孩子的 幸福值 happiness[i] 。你计划组织 k 轮筛选从这 n 个孩子中选出 k 个孩子。

在每一轮选择一个孩子时,所有 尚未 被选中的孩子的 幸福值 将减少 1 。注意,幸福值 不能 变成负数,且只有在它是正数的情况下才会减少。

选择 k 个孩子,并使你选中的孩子幸福值之和最大,返回你能够得到的 最大值

 

示例 1:

输入:happiness = [1,2,3], k = 2
输出:4
解释:按以下方式选择 2 个孩子:
- 选择幸福值为 3 的孩子。剩余孩子的幸福值变为 [0,1] 。
- 选择幸福值为 1 的孩子。剩余孩子的幸福值变为 [0] 。注意幸福值不能小于 0 。
所选孩子的幸福值之和为 3 + 1 = 4 。

示例 2:

输入:happiness = [1,1,1,1], k = 2
输出:1
解释:按以下方式选择 2 个孩子:
- 选择幸福值为 1 的任意一个孩子。剩余孩子的幸福值变为 [0,0,0] 。
- 选择幸福值为 0 的孩子。剩余孩子的幸福值变为 [0,0] 。
所选孩子的幸福值之和为 1 + 0 = 1 。

示例 3:

输入:happiness = [2,3,4,5], k = 1
输出:5
解释:按以下方式选择 1 个孩子:
- 选择幸福值为 5 的孩子。剩余孩子的幸福值变为 [1,2,3] 。
所选孩子的幸福值之和为 5 。

 

提示:

  • 1 <= n == happiness.length <= 2 * 105
  • 1 <= happiness[i] <= 108
  • 1 <= k <= n
lightbulb

解题思路

方法一:贪心 + 排序

为了使得幸福值之和尽可能大,我们应该优先选择幸福值大的孩子。因此,我们可以对孩子按照幸福值从大到小排序,然后依次选择 kk 个孩子。对于当前第 ii 个孩子,能够得到的幸福值为 max(happiness[i]i,0)\max(\textit{happiness}[i] - i, 0),最后返回这 kk 个孩子的幸福值之和。

时间复杂度 O(n×logn+k)O(n \times \log n + k),空间复杂度 O(logn)O(\log n)。其中 nn 是数组 happiness\textit{happiness} 的长度。

1
2
3
4
5
6
7
8
9
class Solution:
    def maximumHappinessSum(self, happiness: List[int], k: int) -> int:
        happiness.sort(reverse=True)
        ans = 0
        for i, x in enumerate(happiness[:k]):
            x -= i
            ans += max(x, 0)
        return ans
speed

复杂度分析

指标
时间O(n \cdot \log n + k \cdot \log n)
空间O(n)
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate selects the top k happiness values correctly.

  • question_mark

    The candidate shows clear reasoning behind the greedy selection approach.

  • question_mark

    The candidate effectively manages the invariant regarding the decrementing happiness values.

warning

常见陷阱

外企场景
  • error

    Failing to sort the array before making selections can lead to suboptimal choices.

  • error

    Not ensuring that happiness values don’t go below zero after decrements.

  • error

    Misunderstanding the problem's greedy approach by picking the wrong children.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if there are multiple children with the same happiness value?

  • arrow_right_alt

    What if we select fewer than k children?

  • arrow_right_alt

    How would the problem change if there was no happiness decrement after each selection?

help

常见问题

外企场景

幸福值最大化的选择方案题解:贪心·invariant | LeetCode #3075 中等