Skip to content

[剑指 Offer] 14- II. 剪绳子 #39

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- II. 剪绳子 #39

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。

答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。

 

示例 1:

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

示例 2:

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

 

提示:

  • 2 <= n <= 1000

解法:
这道题的n取值过大,用动态规划会溢出,实在不会(动态规划也是看的答案,菜鸡啊!!),看了题解,贪心算法,大致意思就是:
把绳子尽量分成大小为3的小段。其实这个从示例二中也能看的出来10=3+3+4。证明就不管了,我又不是搞数学的。代码如下:

class Solution {
public:
    int mod = 1e9 + 7;
    int cuttingRope(int n) {
        long long res = 1; 

        if (n <= 3) {
            return n-1;
        }  else if (n == 4) {
            return 4;
        } else {
            while (n > 4) {
                res = (res * 3) % mod;
                n -= 3; 
            }
            res = (res * n) % mod;    
        }
        
        return res;
    }
};
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