[LeetCode] Integer Break

简介: Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.For example, given n

Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.

For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4).

Note: you may assume that n is not less than 2.

Hint:

  1. There is a simple O(n) solution to this problem.
  2. You may check the breaking results of n ranging from 7 to 10 to discover the regularities.

解题思路

7:34=12
8:332=18
9:333=27
10:334=36

规律:大于4时,不断寻找因子3,并将其相乘。

实现代码

// Runtime: 0 ms
public class Solution {
    public int integerBreak(int n) {
        if (n == 2 || n == 3) {
            return n - 1;
        }
        int base = 1;
        while (n > 4) {
            base *= 3;
            n -= 3;
        }
        return base * n;
    }
}
目录
相关文章
|
机器学习/深度学习
LeetCode 397. Integer Replacement
给定一个正整数 n,你可以做如下操作: 1. 如果 n 是偶数,则用 n / 2替换 n。 2. 如果 n 是奇数,则可以用 n + 1或n - 1替换 n。 n 变为 1 所需的最小替换次数是多少?
53 0
LeetCode 343. Integer Break
给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。
48 0
LeetCode 343. Integer Break
LeetCode之Reverse Integer
LeetCode之Reverse Integer
78 0
|
Java
[LeetCode] Roman to Integer 罗马数字转化成整数
链接:https://leetcode.com/problems/roman-to-integer/#/description难度:Easy题目:13. Roman to Integer Given a roman numeral, convert it to an integer.
764 0
|
Java 编译器
[LeetCode]Reverse Integer题解
题目链接:7. Reverse Integer 难度:Easy Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 N...
757 0
LeetCode - 7. Reverse Integer
7. Reverse Integer Problem's Link  ---------------------------------------------------------------------------- Mean:  将一个整数的数值位反转.
784 0
LeetCode - 12. Integer to Roman
12. Integer to Roman  Problem's Link  ---------------------------------------------------------------------------- Mean:  将一个int型的整数转化为罗马数字.
944 0