LeetCode 题解工作台

K 个元素的最大和

给你一个下标从 0 开始的整数数组 nums 和一个整数 k 。你需要执行以下操作 恰好 k 次,最大化你的得分: 从 nums 中选择一个元素 m 。 将选中的元素 m 从数组中删除。 将新元素 m + 1 添加到数组中。 你的得分增加 m 。 请你返回执行以上操作恰好 k 次后的最大得分。 示例…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 贪心·invariant

bolt

答案摘要

我们注意到,要使得最终的得分最大,我们应该尽可能地使得每次选择的元素最大。因此,我们第一次选择数组中的最大元素 ,第二次选择 ,第三次选择 ,以此类推,直到第 次选择 。这样的选择方式可以保证每次选择的元素都是当前数组中的最大值,因此最终的得分也是最大的。答案即为 个 的和加上 ,即 $k \times x + (k - 1) \times k / 2$。 时间复杂度 ,其中 是数组的长度…

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 0 开始的整数数组 nums 和一个整数 k 。你需要执行以下操作 恰好 k 次,最大化你的得分:

  1. nums 中选择一个元素 m 。
  2. 将选中的元素 m 从数组中删除。
  3. 将新元素 m + 1 添加到数组中。
  4. 你的得分增加 m 。

请你返回执行以上操作恰好 k 次后的最大得分。

 

示例 1:

输入:nums = [1,2,3,4,5], k = 3
输出:18
解释:我们需要从 nums 中恰好选择 3 个元素并最大化得分。
第一次选择 5 。和为 5 ,nums = [1,2,3,4,6] 。
第二次选择 6 。和为 6 ,nums = [1,2,3,4,7] 。
第三次选择 7 。和为 5 + 6 + 7 = 18 ,nums = [1,2,3,4,8] 。
所以我们返回 18 。
18 是可以得到的最大答案。

示例 2:

输入:nums = [5,5,5], k = 2
输出:11
解释:我们需要从 nums 中恰好选择 2 个元素并最大化得分。
第一次选择 5 。和为 5 ,nums = [5,5,6] 。
第二次选择 6 。和为 6 ,nums = [5,5,7] 。
所以我们返回 11 。
11 是可以得到的最大答案。

 

提示:

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100
  • 1 <= k <= 100
lightbulb

解题思路

方法一:贪心 + 数学

我们注意到,要使得最终的得分最大,我们应该尽可能地使得每次选择的元素最大。因此,我们第一次选择数组中的最大元素 xx,第二次选择 x+1x+1,第三次选择 x+2x+2,以此类推,直到第 kk 次选择 x+k1x+k-1。这样的选择方式可以保证每次选择的元素都是当前数组中的最大值,因此最终的得分也是最大的。答案即为 kkxx 的和加上 0+1+2++(k1)0+1+2+\cdots+(k-1),即 k×x+(k1)×k/2k \times x + (k - 1) \times k / 2

时间复杂度 O(n)O(n),其中 nn 是数组的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
class Solution:
    def maximizeSum(self, nums: List[int], k: int) -> int:
        x = max(nums)
        return k * x + k * (k - 1) // 2
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate efficiently handles greedy algorithms and invariant tracking.

  • question_mark

    Candidate considers performance and time complexity when choosing data structures.

  • question_mark

    Candidate demonstrates the ability to optimize code using sorting or priority queues.

warning

常见陷阱

外企场景
  • error

    Failing to properly update the array after each operation, leading to incorrect choices.

  • error

    Using inefficient data structures, causing the solution to exceed time limits.

  • error

    Not validating the greedy approach thoroughly for all edge cases, especially when k is large.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Modify the problem to allow for selecting smaller elements and track the resulting score.

  • arrow_right_alt

    Consider the problem where the number of operations k is variable and depends on the input.

  • arrow_right_alt

    Solve the problem by using dynamic programming instead of a greedy approach.

help

常见问题

外企场景

K 个元素的最大和题解:贪心·invariant | LeetCode #2656 简单