小凉

3 0642700 3 0642770 5 34202 13942 4314 0624

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.

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

实现:

 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.

 

posted on 2016-05-05 18:18  小凉  阅读(173)  评论(0编辑  收藏  举报

导航