Skip to content

[剑指 Offer] 14- I. 剪绳子 #38

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
frdmu opened this issue Jul 23, 2021 · 0 comments
Open

[剑指 Offer] 14- I. 剪绳子 #38

frdmu opened this issue Jul 23, 2021 · 0 comments

Comments

@frdmu
Copy link
Owner

frdmu commented Jul 23, 2021

给你一根长度为 n 的绳子,请把绳子剪成整数长度的 m 段(m、n都是整数,n>1并且m>1),每段绳子的长度记为 k[0],k[1]...k[m-1] 。请问 k[0]k[1]...*k[m-1] 可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。

示例 1:

输入: 2
输出: 1
解释: 2 = 1 + 1, 1 × 1 = 1

示例 2:

输入: 10
输出: 36
解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36

提示:

  • 2 <= n <= 58

解法:
动态规划。
设dp[i]表示i对应的最大乘积。

当i = 0 或 i = 1 时,dp[i] = 0;
当i >= 2时, i被分成 j 和 i-j两段时,会有两种情况:

  • i-j无法继续分;
  • i-j可以继续分。

此时, dp[i] = max(j*(i-j), j*dp[i-j])。代码如下:

class Solution {
public:
    int cuttingRope(int n) {
        vector<int> dp(n+1, 0);
        
        for (int i = 2; i <= n; i++) {
            for (int j = 1; j < i; j++) {
                dp[i] = max(dp[i], max(j*(i-j), j*dp[i-j]));
            }
        }
        
        return dp[n];
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant