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 | Input: 2 |
Example 2:
1 | Input: 10 |
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 | class Solution: |