leetcode笔记: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.

二. 题目分析

题目大意是,给定给一个正整数n,将其分解成至少两个正整数的和,使得这些整数的积达到最大。返回最大的乘积。题目给出了两个案例。这里可以假设n不小于2

看一些规律:

2 = 1 + 1 -> 1 * 1 = 1
3 = 1 + 2 -> 1 * 2 = 2
4 = 2 + 2 -> 2 * 2 = 4
5 = 2 + 3 -> 2 * 3 = 6
6 = 3 + 3 -> 3 * 3 = 9
7 = 3 + 4 -> 3 * 4 = 12
8 = 2 + 3 + 3 -> 2 * 3 * 3 = 18
9 = 3 + 3 + 3 -> 3 * 3 * 3 = 27
10 = 3 + 3 + 4 -> 3 * 3 * 4 = 36
11 = 3 + 3 + 3 + 2 -> 3 * 3 * 3 * 2 = 54
12 = 3 + 3 + 3 + 3 -> 3 * 3 * 3 * 3 = 81 

除开n <= 4的情形,其他情况可用以下规律来描述,对于n的最大分拆乘积,记为f[n],则有:

f[n] = max(2 * f[n - 2], 3 * f[n - 3])

因此该题目可使用动态规划来完成。

三. 示例代码

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

四. 小结

寻找数学规律,该题可以通过多种方法解决。

点赞