Seawolf 发表于 2020-7-31 04:09:37

Leetcode 343. Integer Break

本帖最后由 Seawolf 于 2020-7-31 04:22 编辑

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.

Example 1:

Input: 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1.
Example 2:

Input: 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
Note: You may assume that n is not less than 2 and not larger than 58.

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

示例 1:

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

输入: 10
输出: 36
解释: 10 = 3 + 3 + 4, 3 ×3 ×4 = 36。
说明: 你可以假设n不小于 2 且不大于 58。

class Solution:
    def integerBreak(self, n: int) -> int:
      if n == 2 or n == 3:
            return n - 1
      res = 1
      while n > 4:
            n = n - 3
            res = res * 3
      return res * n

Why factor 2 or 3? The math behind this problem.

页: [1]
查看完整版本: Leetcode 343. Integer Break