大佬教程收集整理的这篇文章主要介绍了[Swift]LeetCode343. 整数拆分 |,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
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.
Example 1:
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.
给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。
示例 1:
输入: 2 输出: 1 解释: 2 = 1 + 1,1 × 1 = 1。
示例 2:
输入: 10 输出: 36 解释: 10 = 3 + 3 + 4,3 × 3 × 4 = 36。
说明: 你可以假设 n 不小于 2 且不大于 58。
8ms
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 }
8ms
1 class Solution { 2 func IntegerBreak(_ n: int) -> Int { 3 4 guard n > 3 else { 5 return [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
以上是大佬教程为你收集整理的[Swift]LeetCode343. 整数拆分 |全部内容,希望文章能够帮你解决[Swift]LeetCode343. 整数拆分 |所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。