整数拆分 🌟🌟🌟中等

课后作业

问题描述

原文链接:343. 整数拆分

给定一个正整数 n ,将其拆分为 k 个 正整数 的和( k >= 2 ),并使这些整数的乘积最大化。

返回 你可以获得的最大乘积 。

示例 1:

输入: n = 2
输出: 1
解释: 2 = 1 + 1, 1 × 1 = 1。
示例 2:

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

提示:

2 <= n <= 58

代码实现

Java

class Solution {
    public int integerBreak(int n) {
        int res = n / 3;
        int mod = n % 3;

        if(n <= 2){
            return 1;
        }

        if(n <= 3){
            return 2;
        }

        if(mod == 0){
            return (int)Math.pow(3, res);
        }else if(mod == 1){
            return (int)Math.pow(3, res - 1) * 4;
        }else{
            return (int)Math.pow(3, res) * 2;
        }
    }
}

Python

class Solution(object):
    def integerBreak(self, n):
        """
        :type n: int
        :rtype: int
        """
        res = n // 3
        mod = n % 3

        if n <= 2:
            return 1
        elif n == 3:
            return 2

        if mod == 0:
            return 3 ** res
        elif mod == 1:
            return 3 ** (res - 1) * 4
        else:
            return 3 ** res * 2

C++

class Solution {
public:
    int integerBreak(int n) {
        int res = n / 3;
        int mod = n % 3;

        if (n <= 2) {
            return 1;
        } else if (n == 3) {
            return 2;
        }

        if (mod == 0) {
            return pow(3, res);
        } else if (mod == 1) {
            return pow(3, res - 1) * 4;
        } else {
            return pow(3, res) * 2;
        }
    }
};

Go

func integerBreak(n int) int {
    res := n / 3
    mod := n % 3

    if n <= 2 {
        return 1
    } else if n == 3 {
        return 2
    }

    if mod == 0 {
        return int(math.Pow(3, float64(res)))
    } else if mod == 1 {
        return int(math.Pow(3, float64(res-1))) * 4
    } else {
        return int(math.Pow(3, float64(res))) * 2
    }
}

发表回复

后才能评论

评论(1)

如果您已经成功付款但是网站没有弹出成功提示,请联系站长提供付款信息为您处理