Integer Break(Difficulty: Easy)

題目:

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.spa

For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4).code

實現:

 1 class Solution {  2 public:  3     int integerBreak(int n) {  4         if (n == 2)  5             return 1;  6         if (n == 3)  7             return 2;  8         int res = 1;  9         while (n>2) 10  { 11             res *= 3; 12             n -= 3; 13  } 14         if (n == 0) 15             return res; 16         if (n == 1) 17             return (res / 3) * 4; 18         if (n == 2) 19             return res*2; 20         return -1; 21  } 22 };

分析:要獲得最大,就須要儘量多地分解出3,可是不能分解出1.那麼分解出了1,就須要把它變成4.blog

相關文章
相關標籤/搜索