343. Integer Break

来源:互联网 发布:c语言与接口这本书怎样 编辑:程序博客网 时间:2024/06/07 14:12

Problem

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.

Solution

为什么将一个数拆除足够多的3就能使乘积最大?

首先,证明大于4的因子是没有意义的。假设x>=4,那么x可以拆分为x-2和2,因为x>=4,所以(x-2)*2>x。所以对于大于4的因子来说,可以将其拆分为更小的因子,来增大最后的乘积。
拆分出1对乘积是没有意义的。

For convenience, say n is sufficiently large and can be broken into any smaller real positive numbers. We now try to calculate which real number generates the largest product. Assume we break n into (n / x) x’s, then the product will be xn/x, and we want to maximize it.

Taking its derivative gives us n * xn/x-2 * (1 - ln(x)). The derivative is positive when 0 < x < e, and equal to 0 when x = e, then becomes negative when x > e, which indicates that the product increases as x increases, then reaches its maximum when x = e, then starts dropping.

This reveals the fact that if n is sufficiently large and we are allowed to break n into real numbers, the best idea is to break it into nearly all e’s. On the other hand, if n is sufficiently large and we can only break n into integers, we should choose integers that are closer to e. The only potential candidates are 2 and 3 since 2 < e < 3, but we will generally prefer 3 to 2. Why?

Of course, one can prove it based on the formula above, but there is a more natural way shown as follows.

6 = 2 + 2 + 2 = 3 + 3. But 2 * 2 * 2 < 3 * 3. Therefore, if there are three 2’s in the decomposition, we can replace them by two 3’s to gain a larger product.

All the analysis above assumes n is significantly large. When n is small (say n <= 10), it may contain flaws. For instance, when n = 4, we have 2 * 2 > 3 * 1. To fix it, we keep breaking n into 3’s until n gets smaller than 10, then solve the problem by brute-force.

DP

class Solution {public:    int integerBreak(int n) {        vector<int> dp(n+1,0);        dp[0] = 0;        dp[1] = 1;        dp[2] = 1;        dp[3] = 2;        dp[4] = 4;        for(int i = 5;i<=n;++i)        {            dp[i] = 3*max(i-3,dp[i-3]);        }        return dp[n];    }};

General

int integerBreak(int n){    if(n == 2) return 1;    if(n == 3) return 2;    int ret = 1;    while( n>4 )    {        ret *= 3;        n -= 3;    }    return ret * n;}
0 0
原创粉丝点击