LeetCode 题解工作台
K 次增加后的最大乘积
给你一个非负整数数组 nums 和一个整数 k 。每次操作,你可以选择 nums 中 任一 元素并将它 增加 1 。 请你返回 至多 k 次操作后,能得到的 nums 的 最大乘积 。由于答案可能很大,请你将答案对 10 9 + 7 取余后返回。 示例 1: 输入: nums = [0,4], k …
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
根据题目描述,要使得乘积最大,我们需要尽量增大较小的数,因此我们可以使用小根堆来维护数组 。每次从小根堆中取出最小的数,将其增加 ,然后重新放回小根堆中。重复这个过程 次后,我们将当前小根堆中的所有数相乘,即可得到答案。 时间复杂度 $O(k \times \log n)$,空间复杂度 。其中 是数组 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你一个非负整数数组 nums 和一个整数 k 。每次操作,你可以选择 nums 中 任一 元素并将它 增加 1 。
请你返回 至多 k 次操作后,能得到的 nums的 最大乘积 。由于答案可能很大,请你将答案对 109 + 7 取余后返回。
示例 1:
输入:nums = [0,4], k = 5 输出:20 解释:将第一个数增加 5 次。 得到 nums = [5, 4] ,乘积为 5 * 4 = 20 。 可以证明 20 是能得到的最大乘积,所以我们返回 20 。 存在其他增加 nums 的方法,也能得到最大乘积。
示例 2:
输入:nums = [6,3,3,2], k = 2 输出:216 解释:将第二个数增加 1 次,将第四个数增加 1 次。 得到 nums = [6, 4, 3, 3] ,乘积为 6 * 4 * 3 * 3 = 216 。 可以证明 216 是能得到的最大乘积,所以我们返回 216 。 存在其他增加 nums 的方法,也能得到最大乘积。
提示:
1 <= nums.length, k <= 1050 <= nums[i] <= 106
解题思路
方法一:贪心 + 优先队列(小根堆)
根据题目描述,要使得乘积最大,我们需要尽量增大较小的数,因此我们可以使用小根堆来维护数组 。每次从小根堆中取出最小的数,将其增加 ,然后重新放回小根堆中。重复这个过程 次后,我们将当前小根堆中的所有数相乘,即可得到答案。
时间复杂度 ,空间复杂度 。其中 是数组 的长度。
class Solution:
def maximumProduct(self, nums: List[int], k: int) -> int:
heapify(nums)
for _ in range(k):
heapreplace(nums, nums[0] + 1)
mod = 10**9 + 7
return reduce(lambda x, y: x * y % mod, nums)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n log n + k log n) due to heap operations for each increment. Space complexity is O(n) for the heap storage. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Expect a solution that maximizes product using minimal increments first.
- question_mark
Using a heap to track the smallest number indicates awareness of greedy invariant.
- question_mark
Be ready to discuss modulo arithmetic and why it's applied during multiplication.
常见陷阱
外企场景- error
Incrementing larger numbers first can reduce the final product and violates greedy choice.
- error
Not using modulo while multiplying can cause integer overflow.
- error
Failing to maintain the heap invariant after each increment results in suboptimal operations.
进阶变体
外企场景- arrow_right_alt
Find maximum sum instead of product after k increments using a similar greedy approach.
- arrow_right_alt
Allow decrement operations as well and maximize product using mixed greedy decisions.
- arrow_right_alt
Compute maximum product if increments must be applied to consecutive elements only.