LeetCode 343 Integer Break 數學
阿新 • • 發佈:2022-06-01
Given an integer n
, break it into the sum of k
positive integers, where \(k\geq 2\), and maximize the product of those integers.
Return the maximum product you can get.
Solution
假設 \(n>4\) 時,且如果存在一個因數 \(f>4\), 那麼我們可以換成 \(2,(f-2)\) 這兩個因子,因為對於 product:
\[2(f-2) = 2f-4>f \]因此可以發現,對於大於4的因數,可以進行分解。但這並不是最優的,考慮一個例子 \(6\)
所以更優的分解是因數 \(3\)。具體來說,求解不等式:
\[3(f-3)\geq f \rightarrow f\ge 5 \]所以當 \(n\ge 5\) 時,分解按照 \(3\) 的最大數量。 但對於 \(4\) 來說,顯然最優分解為:
\[4\rightarrow 2*2>3*1 \]點選檢視程式碼
class Solution { private: int ans=1; public: int integerBreak(int n) { if(n==2)return 1; if(n==3)return 2; if(n==4)return 4; while(n>4){ ans*=3;n-=3; } ans*=n; return ans; } };