Skip to content

Latest commit

 

History

History
66 lines (42 loc) · 1.46 KB

343.md

File metadata and controls

66 lines (42 loc) · 1.46 KB

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。

Code

贪心算法

class Solution {
    public int integerBreak(int n) {
        //当 n <= 3 时,按照贪心规则应直接保留原数字,但由于题目要求必须拆分,因此必须拆出一个 1,即直接返回 n - 1;
        if (n <= 3) return n - 1;
        //求 n 除以 3 的整数部分 a 和余数部分 b;
        int a = n / 3, b = n % 3;
        //当 b == 0时,直接返回 3^a
        if (b == 0) return (int) Math.pow(3, a);
        //当 b == 1 时,要将一个 1 + 3转换为 2+2,此时返回 3^{a-1} * 2 * 2
        if (b == 1) return (int) Math.pow(3, a - 1) * 2 * 2;
        //当 b == 2 时,返回 3^a * b
        return (int) Math.pow(3, a) * b;
    }
}

题解

https://leetcode-cn.com/problems/integer-break/solution/343-zheng-shu-chai-fen-tan-xin-by-jyd/

https://leetcode-cn.com/problems/integer-break/solution/bao-li-sou-suo-ji-yi-hua-sou-suo-dong-tai-gui-hua-/

https://leetcode-cn.com/problems/jian-sheng-zi-lcof/solution/xiang-jie-bao-li-di-gui-ji-yi-hua-ji-zhu-dong-tai-/