首页 > 编程语言 > 详细

[LeetCode][Python]Integer Break

时间:2016-05-13 18:44:43      阅读:208      评论:0      收藏:0      [点我收藏+]

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)

 

 

[LeetCode][Python]Integer Break

原文:http://www.cnblogs.com/Liok3187/p/5490282.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!