★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-mwjungqd-hg.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
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.git
Example 1:github
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.less
給定一個正整數 n,將其拆分爲至少兩個正整數的和,並使這些整數的乘積最大化。 返回你能夠得到的最大乘積。spa
示例 1:code
輸入: 2 輸出: 1 解釋: 2 = 1 + 1, 1 × 1 = 1。
示例 2:htm
輸入: 10 輸出: 36 解釋: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。
說明: 你能夠假設 n 不小於 2 且不大於 58。blog
1 class Solution { 2 func integerBreak(_ n: Int) -> Int { 3 if n < 2 { 4 return 0 5 } 6 7 var res = Array(repeating: 1, count: n+1) 8 9 res[1] = 0 10 11 for i in 2...n { 12 var maxRes = 1 13 for j in 1..<i { 14 maxRes = max(maxRes, max(res[j], j) * max(i-j, res[i-j])) 15 } 16 res[i] = maxRes 17 } 18 return res[n] 19 } 20 }
8msget
1 class Solution { 2 func integerBreak(_ n: Int) -> Int { 3 4 guard n > 3 else { 5 return [1,1,1,2][n] 6 } 7 8 var times3 = n / 3 9 10 if n % 3 == 1 { 11 times3 -= 1 12 } 13 14 let times2 = (n - times3 * 3) / 2 15 16 return Int(pow(3.0, Double(times3))) * Int(pow(2.0, Double(times2))) 17 } 18 }
16ms
1 class Solution { 2 func integerBreak(_ n: Int) -> Int { 3 if n == 2 { 4 return 1 5 } else if n == 3 { 6 return 2 7 } else if n % 3 == 0 { 8 return Int(pow(3, Double(n / 3))) 9 } else if n % 3 == 1 { 10 return Int(2 * 2 * pow(3, Double((n - 4) / 3))) 11 } else { // 2 12 return Int(2 * pow(3, Double((n - 2) / 3))) 13 } 14 } 15 }
24ms
1 class Solution { 2 func integerBreak(_ n: Int) -> Int { 3 var dps = Array(repeating: 0, count: n + 1) 4 dps[1] = 1 5 for num in 2...n { 6 for j in 1..<num { 7 dps[num] = max(dps[num], j * max(num - j, dps[num - j])) 8 } 9 } 10 11 return dps[n] 12 } 13 }