[LeetCode] 343. Integer Break

来源:互联网 发布:java 时间格式 编辑:程序博客网 时间:2024/05/17 20:53

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.

Hint:

  1. There is a simple O(n) solution to this problem.
  2. You may check the breaking results of n ranging from 7 to 10 to discover the regularities.

1、动态规划
一开始是用动态规划做的,比较简单,写出递推关系式:dp[i] = max{ dp[i], (j*dp[i - j])),前几种情况分别列出来,时间复杂度Ο(n^2),具体代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int integerBreak(int n) {
    vector<int> dp(n + 1, 1);
    if (n == 2 || n == 3) return n - 1;
    else{
        dp[2] = 2;
        dp[3] = 3;
    }
    for (int i = 4; i < dp.size(); i++){
        for (int j = 1; j < i; j++){
            int temp = j*dp[i - j];
            dp[i] = dp[i]>(j*dp[i - j]) ? dp[i] : (j*dp[i - j]);
        }
    }
    return dp[n];
}

2、找规律求解
提示中说了是有规律的,所以写写看:
7:12 = 3*4
8:18 = 3*3*2
9:27 = 3*3*3
10:36 = 3*3*4
所以把n拆分成n/3个3和n%3,代码:

1
2
3
4
5
6
7
int integerBreak(int n) {
    vector<int> nums{ 1, 1, 1, 2, 4 };
    if (n <= 4) return nums[n];
    if (n % 3 == 0) return pow(3, n / 3);
    if (n % 3 == 1) return 4 * pow(3, n / 3 - 1);
    if (n % 3 == 2) return 2 * pow(3, n / 3);
}

0 0
原创粉丝点击