Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✅343. 整数拆分 #17

Open
Ray-56 opened this issue Jun 4, 2020 · 1 comment
Open

✅343. 整数拆分 #17

Ray-56 opened this issue Jun 4, 2020 · 1 comment

Comments

@Ray-56
Copy link
Owner

Ray-56 commented Jun 4, 2020

343. 整数拆分

题目

给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。

示例1:

输入: 2
输出: 1
解释: 2 = 1 + 1, 1 × 1 = 1

示例2:

输入: 10
输出: 36
解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36

提示:你可以假设 n 不小于 2 且不大于 58。

@Ray-56
Copy link
Owner Author

Ray-56 commented Jun 4, 2020

dp 解法

  • dp[i] = maxn 为 i 时 的最大乘积
  • i = j + (i - j)拆分 i ,乘积就是j * (i - j)但是不一定是最大的,与j * dp[i - j]相比得到最大乘积
  • 由题意可知前两个的最大乘积都为1
/**
 * @param {number} n
 * @return {number}
 */
var integerBreak = function(n) {
	const dp = Array(n + 1).fill(1);

	for (let i = 3; i <= n; i++) {
		for (let j = 2; j < i; j++) {
			dp[i] = Math.max(
				dp[i],
				j * (i - j),
				j * dp[i - j]
			);
		}
	}
	return dp[n];
};

@Ray-56 Ray-56 changed the title 343. 整数拆分 ✅343. 整数拆分 Jun 8, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant