343. 整数拆分(中等题)

给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。

示例 1:

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

示例 2:

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

说明: 你可以假设 n 不小于 2 且不大于 58。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/integer-break
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法:

class Solution {
    public int integerBreak(int n) {
        if(n == 2){
            return 1;
        }
        if(n == 3){
            return 2;
        }
        int count_3 = n/3;
        int count_2 = 0;
        int remainder = n%3;
        if(remainder == 1){
            count_3--;
            count_2 = 2;
        }
        else if(remainder == 2){
            count_2 = 1;
        }
        return (int)(Math.pow(3,count_3)*Math.pow(2,count_2));
    }
}
发布了258 篇原创文章 · 获赞 5 · 访问量 5336

猜你喜欢

转载自blog.csdn.net/weixin_43105156/article/details/104354684