[LeetCode][Python]Integer Break

本文介绍了一种算法问题——整数拆分求最大乘积,通过两种方法实现:一是动态规划解决,二是利用规律简化计算。适用于LeetCode上的Integer Break题目。

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 = 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.

https://leetcode.com/problems/integer-break/ 

 

 


 

 

把一个数字拆成几个数字相加,这几个数的乘积要最大。

先是O(n^2)的动态规划。某个数最大的乘积,总是由比它小的数的子结果,乘以他们之间的差得来的。

但是注意也有可能是拆成两个数直接相乘的结果(从后面推断可以知道是小于6的数)。

 1 class Solution(object):
 2     def integerBreak(self, n):
 3         """
 4         :type n: int
 5         :rtype: int
 6         """
 7         dp = [0, 1, 1]
 8         for i in range(3, n + 1):
 9             maxInt = -1 
10             for j in range(1, i):
11                 maxInt = max(maxInt, (i - j) * dp[j], (i - j) * j)
12             dp.append(maxInt)
13         return dp[n]

 

 

然后找规律,从大于7的数开始,符合规律。

为什么要以3为单位,不是4也不是5,因为:

3 * 3 * 3 * 3 > 4 * 4 * 4
3 * 3 * 3 * 3 * 3 > 5 * 5 * 5

https://leetcode.com/discuss/98249/easy-to-understand-c-with-explanation

 1 class Solution(object):
 2     def integerBreak(self, n):
 3         """
 4         :type n: int
 5         :rtype: int
 6         """
 7         dp = [0, 1, 1, 2, 4, 6, 9]
 8         if n <= 6:
 9             return dp[n]
10         return 3 * self.integerBreak(n - 3)

 

 

转载于:https://www.cnblogs.com/Liok3187/p/5490282.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值