Daily LeetCode 343. Integer Break

https://leetcode.com/problems/integer-break/

Medium

问题描述

Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.

Example 1:

1
2
3
Input: 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1.

Example 2:

1
2
3
Input: 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.

Note: You may assume that n is not less than 2 and not larger than 58.

思路及代码:

这是一条拆分数字的题目,要求把一个正数拆分为至少两个正数的和,保证拆分后的乘积最大。既然是拆分,那么肯定会用到更小的数拆分的结果,维护一个数组dp,dp[i]保存着拆分i后的最大乘积。

对于给定数字n,我们从3开始遍历,每一次遍历i,都考虑所有拆分i的情况,即考虑j*(i-j), j区间[1, i-1],更新dp[i],dp[i]=max(dp[i],j*(i-j),dp[i-j]*j)

代码如下:

1
2
3
4
5
6
7
8
class Solution:
def integerBreak(self, n: int) -> int:
dp = [1] * (n + 1)
for i in range(3, n + 1):
for j in range(i):
dp[i] = max(dp[i], max(j * (i - j), dp[i - j] * j))

return dp[-1]