1 Star 0 Fork 332

卜月航 / leetcode

forked from doocs / leetcode 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
README.md 3.21 KB
一键复制 编辑 原始数据 按行查看 历史

面试题 14- I. 剪绳子

题目描述

给你一根长度为 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

注意:本题与主站 343 题相同:https://leetcode.cn/problems/integer-break/

解法

尽可能将绳子以长度 3 等分剪为多段时,乘积最大。

Python3

class Solution:
    def cuttingRope(self, n: int) -> int:
        if n < 4:
            return n - 1
        ans = 1
        while n > 4:
            ans *= 3
            n -= 3
        ans *= n
        return ans

Java

class Solution {
    public int cuttingRope(int n) {
        if (n < 4) {
            return n - 1;
        }
        int ans = 1;
        while (n > 4) {
            ans *= 3;
            n -= 3;
        }
        ans *= n;
        return ans;
    }
}

JavaScript

/**
 * @param {number} n
 * @return {number}
 */
var cuttingRope = function (n) {
    if (n < 4) return n - 1;
    let ans = 1;
    while (n > 4) {
        ans *= 3;
        n -= 3;
    }
    ans *= n;
    return ans;
};

Go

func cuttingRope(n int) int {
	if n < 4 {
		return n - 1
	}
	ans := 1
	for n > 4 {
		ans *= 3
		n -= 3
	}
	ans *= n
	return ans
}

C++

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

Rust

impl Solution {
    pub fn cutting_rope(mut n: i32) -> i32 {
        if n < 4 {
            return n - 1;
        }
        let mut res = 1;
        while n > 4 {
            res *= 3;
            n -= 3;
        }
        res * n
    }
}

C#

public class Solution {
    public int CuttingRope(int n) {
        if (n < 4) {
            return n - 1;
        }
        int ans = 1;
        while (n > 4) {
            ans *= 3;
            n -= 3;
        }
        ans *= n;
        return ans;
    }
}

...

马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/BuYh/leetcode.git
git@gitee.com:BuYh/leetcode.git
BuYh
leetcode
leetcode
main

搜索帮助

344bd9b3 5694891 D2dac590 5694891