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 and not larger than 58.


Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Source: leetcode | Difficulty: MEDIUM_HARD
Tags: Dynamic programming

Mathematics

Starter code: class Solution:
    def integerBreak(self, n: int) -> int:
        

Solutions:
class Solution:

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


class Solution:

	def integerBreak(self, n):
		import math
		if n == 2 or n == 3:
			return n - 1
		else:
			if n % 3 == 1:
				m1 = 2
			elif n % 3 == 2:
				m1 = 1
			else:
				m1 = 0
			m2 = (n - 2 * m1) // 3
			return 2 ** m1 * 3 ** m2


class Solution:

	def integerBreak(self, n):
		memo = [0] * (n + 1)
		memo[0] = 0
		memo[1] = 1
		for i in range(2, n + 1):
			maxprod = 1
			for j in range(1, i):
				maxprod = max(maxprod, max(j, memo[j]) * max(i - j, memo[i - j]))
			memo[i] = maxprod
		return memo[n]


class Solution:

	def integerBreak(self, n):
		res = []
		for i in range(n + 1):
			res.append(-1)
		for i in range(n + 1):
			for j in range(i):
				res[j] = max(j, res[j])
				res[i] = max(res[i], res[j] * (i - j))
		return res[n]


class Solution:

	def integerBreak(self, n):
		dp = [0 for i in range(n + 1)]
		dp[1] = 1
		for i in range(2, n + 1):
			for j in range(1, i):
				dp[i] = max(max(dp[j], j) * max(dp[i - j], i - j), dp[i])
		return dp[-1]


class Solution:

	def integerBreak(self, n):
		if n < 4:
			return n - 1
		ans = 1
		while n > 4:
			ans *= 3
			n -= 3
		ans *= n
		return ans


class Solution:

	def integerBreak(self, n):
		ans = [1] * (n + 1)
		for i in range(2, n + 1):
			ans[i] = ans[i - 1]
			for j in range(1, 10):
				if i - j > 0 and ans[i - j] * j > ans[i]:
					ans[i] = ans[i - j] * j
				if i < n:
					ans[i] = max(ans[i], i)
		return ans[n]


class Solution:

	def integerBreak(self, n):
		memo = [0] * 59
		memo[1] = 1
		if n == 2:
			return 1
		if n == 3:
			return 2
		for i in range(2, n + 1):
			tmp = []
			for j in range(1, i):
				memo[i] = max(i, memo[i], memo[j] * memo[i - j])
		return memo[n]


class Solution:

	def integerBreak(self, n):
		if n <= 3:
			return n - 1
		if n == 4:
			return 4
		if n > 4:
			if n % 3 == 0:
				return 3 ** int(n / 3)
			if n % 3 != 0 and (n - 2) % 3 == 0:
				return 3 ** int((n - 2) / 3) * 2
			else:
				return 3 ** int((n - 2) / 3) * 4


class Solution:

	def integerBreak(self, n):
		if n < 4:
			return n - 1
		res = 0
		if n % 3 == 0:
			res = 3 ** (n // 3)
		elif n % 3 == 2:
			res = 3 ** (n // 3) * 2
		else:
			res = 3 ** (n // 3 - 1) * 4
		return res