LeetCode 题解工作台
整数拆分
给定一个正整数 n ,将其拆分为 k 个 正整数 的和( k >= 2 ),并使这些整数的乘积最大化。 返回 你可以获得的最大乘积 。 示例 1: 输入: n = 2 输出: 1 解释: 2 = 1 + 1, 1 × 1 = 1。 示例 2: 输入: n = 10 输出: 36 解释: 10 = 3…
2
题型
9
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们定义 表示正整数 拆分后能获得的最大乘积,初始时 $f[1] = 1$。答案即为 。 考虑 最后拆分出的数字 ,其中 $j \in [1, i)$。对于 拆分出的数字 ,有两种情况:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给定一个正整数 n ,将其拆分为 k 个 正整数 的和( k >= 2 ),并使这些整数的乘积最大化。
返回 你可以获得的最大乘积 。
示例 1:
输入: n = 2 输出: 1 解释: 2 = 1 + 1, 1 × 1 = 1。
示例 2:
输入: n = 10 输出: 36 解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。
提示:
2 <= n <= 58
解题思路
方法一:动态规划
我们定义 表示正整数 拆分后能获得的最大乘积,初始时 。答案即为 。
考虑 最后拆分出的数字 ,其中 。对于 拆分出的数字 ,有两种情况:
- 将 拆分成 和 的和,不继续拆分,此时乘积为 ;
- 将 拆分成 和 的和,继续拆分,此时乘积为 。
因此,我们可以得到状态转移方程:
最后返回 即可。
时间复杂度 ,空间复杂度 。其中 为给定的正整数。
class Solution:
def integerBreak(self, n: int) -> int:
f = [1] * (n + 1)
for i in range(2, n + 1):
for j in range(1, i):
f[i] = max(f[i], f[i - j] * j, (i - j) * j)
return f[n]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Does the candidate recognize the optimal use of 3s to maximize the product?
- question_mark
Can they effectively use dynamic programming or memoization to solve the problem efficiently?
- question_mark
Are they able to optimize the solution for larger values of `n` without redundant calculations?
常见陷阱
外企场景- error
Forgetting that the product is maximized by breaking `n` into 3s and 2s, not just splitting `n` evenly.
- error
Overcomplicating the problem by attempting brute-force enumeration instead of dynamic programming.
- error
Not considering edge cases like `n = 2` or `n = 3` where the breakdown may seem trivial but is important.
进阶变体
外企场景- arrow_right_alt
Generalizing to finding the maximum product for other mathematical break-downs, such as sums of squares.
- arrow_right_alt
Changing the problem constraints to allow for fractional parts, altering the breakdown strategy.
- arrow_right_alt
Adapting this problem to work with larger constraints like `n = 100` and ensuring that the solution still works efficiently.