LeetCode 343. Integer Break

原题链接在这里:https://leetcode.com/problems/integer-break/description/

题目:

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.

题解:

Could write some examples with smaller n.

Then realize this could sloved with dp. Let dp[i] denotes largest product up to index i.

dp[i] = max(max(j, dp[j]) * max(i-1, dp[i-j])). 

e.g. 6 = 1+5, 2+4, 3+3. 

2, 3, 4 could break into smaller integers, dp[2], dp[3], dp[4] stands for their maximum product. But it doesn't include the integer itself only. like 2. dp[2] = 1*1 = 1. but 2 could be used alone when it comes to 6 = 2+4. 

Thus here it needs to get bigger value between j and dp[j] first.

Time Complexity: O(n^2).

Space: O(n).

AC Java: 

 1 class Solution {
 2     public int integerBreak(int n) {        
 3         int [] dp = new int[n+1];
 4         dp[1] = 1;
 5         for(int i = 2; i<=n; i++){
 6             for(int j = 1; j<i; j++){
 7                 dp[i] = Math.max(dp[i], Math.max(j, dp[j]) * Math.max(i-j, dp[i-j]));
 8             }
 9         }
10         
11         return dp[n];
12     }
13 }

若果n足够大,把n拆成小的数字. n 拆成 n/x 个 x, product 就是 x^(n/x). 目标就是使这个product 最大. 取derivative 得到 n * x^(n/x-2) * (1-ln(x)).

0<x<e 时derivative为正 product 增加. x>e时 derivative为负, product 减小. x=e时 derivative为零, product 最大.

最接近e的整数是2 和 3. 但尽量选3. 6 = 2+2+2 = 3+3. 2*2*2 < 3*3.

但4包括以下是特例. 4 = 1+3 = 2+2. 1*3 < 2*2.

所以4以上尽量减掉3, 4时直接乘以剩下的数.

Time Complexity: O(n). 每次减掉3, O(n/3)次.

Space: O(1).

AC Java:

 1 class Solution {
 2     public int integerBreak(int n) {
 3         if(n == 2){
 4             return 1;
 5         }
 6         if(n == 3){
 7             return 2;
 8         }
 9         
10         int res = 1;
11         while(n > 4){
12             res *= 3;
13             n -= 3;
14         }
15         
16         res *= n;
17         return res;
18     }
19 }

 

posted @ 2017-09-26 14:38  Dylan_Java_NYC  阅读(189)  评论(0编辑  收藏  举报