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 + nln2

lnf = mln3 + ((x - 3m) / 2) *ln2

lnf = x/2 * ln2 + (ln3 - 3/2 * ln2)m

则f是m的增函数,所以3越多越好。

看别人写说,如果拆出的不限于整数的话,那么e = 2.718……是最好的选择。


原创粉丝点击