LeetCode 343. 整數拆分(C++、python)
阿新 • • 發佈:2018-11-25
給定一個正整數 n,將其拆分為至少兩個正整數的和,並使這些整數的乘積最大化。 返回你可以獲得的最大乘積。
示例 1:
輸入: 2 輸出: 1 解釋: 2 = 1 + 1, 1 × 1 = 1。
示例 2:
輸入: 10 輸出: 36 解釋: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。
說明: 你可以假設 n 不小於 2 且不大於 58。
思路:本題主要是找到規律,3*3>2*2*2。程式碼如下
C++
class Solution { public: int integerBreak(int n) { if(2==n) { return 1; } else if(3==n) { return 2; } else if(4==n) { return 4; } else if(5==n) { return 6; } else { int count=n/6; int m=n%6; int res=pow(9,count); if(1==m) { res=res/3*4; } else if(2==m) { res*=2; } else if(3==m) { res*=3; } else if(4==m) { res*=4; } else if(5==m) { res*=6; } return res; } } };
python
class Solution: def integerBreak(self, n): """ :type n: int :rtype: int """ if 2==n: return 1 elif 3==n: return 2 elif 4==n: return 4 elif 5==n: return 6 else: count=n//6 m=n%6 res=9**count if 1==m: res=res//3*4 elif 2==m: res*=2 elif 3==m: res*=3 elif 4==m: res*=4 elif 5==m: res*=6 return res