LeetCode 题解工作台

整数拆分

给定一个正整数 n ,将其拆分为 k 个 正整数 的和( k >= 2 ),并使这些整数的乘积最大化。 返回 你可以获得的最大乘积 。 示例 1: 输入: n = 2 输出: 1 解释: 2 = 1 + 1, 1 × 1 = 1。 示例 2: 输入: n = 10 输出: 36 解释: 10 = 3…

category

2

题型

code_blocks

9

代码语言

hub

3

相关题

当前训练重点

中等 · 状态·转移·动态规划

bolt

答案摘要

我们定义 表示正整数 拆分后能获得的最大乘积,初始时 $f[1] = 1$。答案即为 。 考虑 最后拆分出的数字 ,其中 $j \in [1, i)$。对于 拆分出的数字 ,有两种情况:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个正整数 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
lightbulb

解题思路

方法一:动态规划

我们定义 f[i]f[i] 表示正整数 ii 拆分后能获得的最大乘积,初始时 f[1]=1f[1] = 1。答案即为 f[n]f[n]

考虑 ii 最后拆分出的数字 jj,其中 j[1,i)j \in [1, i)。对于 ii 拆分出的数字 jj,有两种情况:

  1. ii 拆分成 iji - jjj 的和,不继续拆分,此时乘积为 (ij)×j(i - j) \times j
  2. ii 拆分成 iji - jjj 的和,继续拆分,此时乘积为 f[ij]×jf[i - j] \times j

因此,我们可以得到状态转移方程:

f[i]=max(f[i],f[ij]×j,(ij)×j)(j[0,i))f[i] = \max(f[i], f[i - j] \times j, (i - j) \times j) \quad (j \in [0, i))

最后返回 f[n]f[n] 即可。

时间复杂度 O(n2)O(n^2),空间复杂度 O(n)O(n)。其中 nn 为给定的正整数。

1
2
3
4
5
6
7
8
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]
speed

复杂度分析

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

面试官常问的追问

外企场景
  • 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?

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

整数拆分题解:状态·转移·动态规划 | LeetCode #343 中等