[Leetcode] [Python] Integer break

Source: Internet
Author: User

Integer break

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

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

Note:you may assume, 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 for n ranging from 7 to discover the regularities.

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

Divide a number into several numbers, and the product of these numbers is the largest.

First O (n^2) dynamic planning. The greatest product of a number is always multiplied by the sub-result of a number smaller than it is by the difference between them.

However, it is also possible that the result of a direct multiplication of two numbers (inferred from the following can be known to be less than 6).

1 classsolution (object):2     defIntegerbreak (self, n):3         """4 : Type N:int5 : Rtype:int6         """7DP = [0, 1, 1]8          forIinchRange (3, n + 1):9MaxInt =-1Ten              forJinchRange (1, i): OneMAXINT = Max (MaxInt, (i-j) * Dp[j], (I-J) *j) A dp.append (maxInt) -         returnDp[n]

Then find the law, starting from a number greater than 7, to conform to the law.

Why do you want to use 3 units, not 4 or 5, because:

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 classsolution (object):2     defIntegerbreak (self, n):3         """4 : Type N:int5 : Rtype:int6         """7DP = [0, 1, 1, 2, 4, 6, 9]8         ifN <= 6:9             returnDp[n]Ten         return3 * Self.integerbreak (n-3)

[Leetcode] [Python] Integer break

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.