LeetCode
来源:互联网 发布:反恐数据库外泄 编辑:程序博客网 时间:2024/06/06 12:20
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.
拆分一个整数使其加数积最大。
找一波规律。
class Solution {public: int integerBreak(int n) { if (n == 2) return 1; if (n == 3) return 2; int ans = 1; while (n > 4) { ans *= 3; n -= 3; } return ans * n; }};
其实有个证明,拆出足够多的3能使乘积最大。
首先证明一下拆出的因子大于4是不可行的。当>4时,还可以拆成乘积更大的。如下:
(N/2)*(N/2)>=N, then N>=4
(N-1)/2 *(N+1)/2>=N, then N>=5
则只剩下3和2,假如 x = 3m + 2n
f = 3^m * 2^n 两边同时取对数
lnf = mln3 + nln2lnf = mln3 + ((x - 3m) / 2) *ln2
lnf = x/2 * ln2 + (ln3 - 3/2 * ln2)m
则f是m的增函数,所以3越多越好。
看别人写说,如果拆出的不限于整数的话,那么e = 2.718……是最好的选择。
阅读全文
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- Linux命令分析: chgrp
- CodeForces
- MUI 代码键总结
- html框架综合练习(frameset)
- 安卓打印加载等待对的实现
- LeetCode
- spring boot通过jar包启动时,配置文件的加载顺序
- URL编码表
- 开启redis 允许外网IP 访问
- CentOS 6.6挂载iSCSI存储
- Js函数
- [算法与数据结构]
- 远程过程调用(RPC)详解
- HTTP常见状态码