[Leetcode] Integer Break 分解整数最大乘积
Integer Break
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.
For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4).
Note: you may assume that n is not less than 2.
Hint:
There is a simple O(n) solution to this problem.
You may check the breaking results of n ranging from 7 to 10 to discover the regularities.
DP
复杂度
O(N) 时间 O(N) 空间
思路
dp[i]表示i这个数字拆分后的最大乘积,最后的答案是dp[n].
初始化:
dp[0] = 0 //这个无所谓
dp[1] = 1 //得是1,方便后面乘法
dp[2] = 1,
dp[i] = Max(dp[k] dp[i - k], k (i - k), dp[k] (i - k), k (dp[i - k])), k取值从[1, i / 2]闭区间
看图说话:
注意
注意对于一个拆分有四种情况,不是两种!
代码
public int integerBreak(int n) {
int[] dp = new int[n + 1];
dp[0] = 0;//用不着,随便设
dp[1] = 1;
dp[2] = 1;
for (int i = 3; i
关键字:leetcode, int, tmpmax, max
版权声明
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处。如若内容有涉嫌抄袭侵权/违法违规/事实不符,请点击 举报 进行投诉反馈!