LeetCode 题解工作台
收集巧克力
给你一个长度为 n 、下标从 0 开始的整数数组 nums , nums[i] 表示收集位于下标 i 处的巧克力成本。每个巧克力都对应一个不同的类型,最初,位于下标 i 的巧克力就对应第 i 个类型。 在一步操作中,你可以用成本 x 执行下述行为: 同时修改所有巧克力的类型,将巧克力的类型 i th…
2
题型
6
代码语言
3
相关题
当前训练重点
中等 · 数组·结合·enumeration
答案摘要
我们考虑枚举操作的次数,定义 表示第 个巧克力进行了 次操作后的最小成本。 对于第 个巧克力:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·结合·enumeration 题型思路
题目描述
给你一个长度为 n、下标从 0 开始的整数数组 nums,nums[i] 表示收集位于下标 i 处的巧克力成本。每个巧克力都对应一个不同的类型,最初,位于下标 i 的巧克力就对应第 i 个类型。
在一步操作中,你可以用成本 x 执行下述行为:
- 同时修改所有巧克力的类型,将巧克力的类型
ith修改为类型((i + 1) mod n)th。
假设你可以执行任意次操作,请返回收集所有类型巧克力所需的最小成本。
示例 1:
输入:nums = [20,1,15], x = 5 输出:13 解释:最开始,巧克力的类型分别是 [0,1,2] 。我们可以用成本 1 购买第 1 个类型的巧克力。 接着,我们用成本 5 执行一次操作,巧克力的类型变更为 [1,2,0] 。我们可以用成本 1 购买第 2 个类型的巧克力。 然后,我们用成本 5 执行一次操作,巧克力的类型变更为 [2,0,1] 。我们可以用成本 1 购买第 0 个类型的巧克力。 因此,收集所有类型的巧克力需要的总成本是 (1 + 5 + 1 + 5 + 1) = 13 。可以证明这是一种最优方案。
示例 2:
输入:nums = [1,2,3], x = 4 输出:6 解释:我们将会按最初的成本收集全部三个类型的巧克力,而不需执行任何操作。因此,收集所有类型的巧克力需要的总成本是 1 + 2 + 3 = 6 。
提示:
1 <= nums.length <= 10001 <= nums[i] <= 1091 <= x <= 109
解题思路
方法一:枚举
我们考虑枚举操作的次数,定义 表示第 个巧克力进行了 次操作后的最小成本。
对于第 个巧克力:
- 如果 ,即没有进行操作,那么 ;
- 如果 ,那么它的最小成本就是下标范围为 的最小成本,即 ,或者可以写成 。
- 如果 ,由于当 时,已经覆盖了所有最小成本,如果 继续增大,那么最小成本不会再变化,但是操作次数的增加却会导致最终的成本增加,因此,我们不需要考虑 的情况。
综上,我们可以得到状态转移方程:
最后,我们只需要枚举操作的次数 ,计算出每种操作次数下的最小成本,取最小值即可。即答案为 。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def minCost(self, nums: List[int], x: int) -> int:
n = len(nums)
f = [[0] * n for _ in range(n)]
for i, v in enumerate(nums):
f[i][0] = v
for j in range(1, n):
f[i][j] = min(f[i][j - 1], nums[(i - j) % n])
return min(sum(f[i][j] for i in range(n)) + x * j for j in range(n))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n^2) because for each of n rotations, we may sum costs across n elements. Space complexity is O(n) for storing rotated cost arrays and tracking totals. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Will you consider the rotation cost when deciding which chocolate to pick first?
- question_mark
How many rotations will be necessary at maximum before costs repeat?
- question_mark
Can you optimize the calculation of cumulative costs across rotations using enumeration?
常见陷阱
外企场景- error
Forgetting to include the rotation cost x in total calculations.
- error
Overcounting purchases when a rotation shifts already collected chocolates.
- error
Failing to check all possible rotation counts for minimal total cost.
进阶变体
外企场景- arrow_right_alt
Minimize total cost when multiple chocolates of the same type exist with different prices.
- arrow_right_alt
Compute minimum cost if rotations are restricted to k times only.
- arrow_right_alt
Find total cost if some chocolates cannot be rotated due to constraints.