1. 程式人生 > >Leetcode 343 Integer Break

Leetcode 343 Integer Break

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.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

題意就是講一個整數分為若干個數(至少兩個),使得這若干個數的乘積最大。利用動態規劃不難求解,對於數n ,狀態轉移方程如下,複雜度o(n^2):

for(i=1 to n-1)
求出max{i*dp(n-i)}即可
//這裡需要注意的是n<4時,要另外考慮
class Solution {
public:
    int integerBreak(int n) {
        vector
<int>
array(n); array[0] = 1; array[1] = 1; array[2] = 2; if (n == 1||n==2) { return 1; } if (n == 3) { return 2; } int max,temp; for (int i = 4; i <= n; i++) { max = 0; for
(int j = 1; j < i ; j++) { if (i - j < 4) { temp = i - j; } else { temp = array[i - j - 1]; } if (j*temp > max) { max = j*temp; } } array[i - 1] = max; } return array[n - 1]; } };

但是有一個更優的解法時間複雜度為o(n),注意到:其實分解因子的時候每個因子都不會大於3

public class Solution {
    public int integerBreak(int n) {
        if(n==2) return 1;
        if(n==3) return 2;
        int product = 1;
        while(n>4){
            product*=3;
            n-=3;
        }
        product*=n;

        return product;
    }
}