343. Integer Break
来源:互联网 发布:swatch知乎 编辑:程序博客网 时间:2024/06/06 18:00
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 and not larger than 58.
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.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
If an optimal product contains a factor f >= 4, then you can replace it with factors 2 and f-2 without losing optimality, as 2*(f-2) = 2f-4 >= f. So you never need a factor greater than or equal to 4, meaning you only need factors 1, 2 and 3 (and 1 is of course wasteful and you'd only use it for n=2 and n=3, where it's needed).
For the rest I agree, 3*3 is simply better than 2*2*2, so you'd never use 2 more than twice.
代码如下:
public class Solution { public int integerBreak(int n) { if (n == 2) { return 1; } if (n == 3) { return 2; } int product = 1; while (n > 4) { n = n - 3; product *= 3; } return product * n; }}另一种方案是dp,代码如下:
public class Solution { public int integerBreak(int n) { /* 0 1 1 1 2 1 * 1 = 1 3 1 * 2 = 2 4 2 * 2 = 4 5 2 * 3 = 6 6 3 * 3 = 9 7 2 * 2 * 3 = 12 8 2 * 3 * 3 = 18 9 3 * 3 * 3 = 27 10 3 * 4 * 3 = 36 */ if (n < 2) { return n; } int[] dp = new int[n + 1]; dp[0] = 0; dp[1] = 0; for (int i = 2; i <= n; i ++) { int j = 1, max = Integer.MIN_VALUE; while (j < i) { max = Math.max(max, j * dp[i - j]); j ++; } dp[i] = Math.max(max, i * i / 4); } for (int num: dp) { System.out.println(num); } return dp[n]; }}简化版本如下:
public int integerBreak(int n) { int[] dp = new int[n + 1]; dp[1] = 1; for(int i = 2; i <= n; i ++) { for(int j = 1; j < i; j ++) { dp[i] = Math.max(dp[i], (Math.max(j,dp[j])) * (Math.max(i - j, dp[i - j]))); } } return dp[n];}
- Leetcode 343. Integer Break
- [LeetCode] 343. Integer Break
- leetcode 343. Integer Break
- LeetCode-343. Integer Break
- LeetCode 343. Integer Break
- 343. Integer Break
- 343. Integer Break 【M】
- 343. Integer Break
- leetcode 343. Integer Break
- 343. Integer Break
- 343. Integer Break
- Leetcode:343. Integer Break
- 343. Integer Break
- LeetCode 343. Integer Break
- 343. Integer Break
- leetcode-343. Integer Break
- LeetCode: 343. Integer Break
- 343. Integer Break
- group by
- 总结mysql数据库中InnoDB与Myisam表类型的的六大区别
- mybatis + postgresql
- freeradius
- C中可变参数函数及log函数运用
- 343. Integer Break
- 为什么需要字节对齐?
- C语言链表创建的电子通讯录V1.0
- poj3984 迷宫问题
- SAP录屏BDC使用实例
- Android开发中向SQlite表自动插入当前时间
- HJT212协议
- matlab实现PS算法之亮度调整
- JAVA字符串格式化-String.format()的使用