343. Integer Break

    Given a positive integer n 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.


​ Assume that we have divided n into a parts, they are respectively n_1, n_2, …, n_a. Then we get a product

pro=n1×n2×...×na p r o = n 1 × n 2 × . . . × n a

Now just choose an element ni which is greater than 4 from the set.
If n_i is even, we divide it into two parts:
ni2,ni2 n i 2 , n i 2

else, we divide it into two parts:
ni12,ni+12 n i − 1 2 , n i + 1 2

And it’s clear that
ni2×ni2ni,  ni4 n i 2 × n i 2 ⩾ n i ,     n i ⩾ 4

ni12×ni+12ni,  ni5 n i − 1 2 × n i + 1 2 ⩾ n i ,     n i ⩾ 5

So to get greater product, we would like to break ni n i into smaller pieces.
Above all, every piece in the set we get after breaking n n <script type="math/tex" id="MathJax-Element-9">n</script> into many pieces should be smaller than or equal to 3. Of course, don’t choose 1 cause of anything’s production with 1 is itself.
How about 2? For example, 9 = 3 + 3 + 3 = 2 + 2 + 2 + 3, and 3 * 3 * 3 = 27 > 2 * 2 * 2 * 3 = 24.

int integerBreak(int n)
{
    if(n == 2)return 1;
    if(n == 3)return 2;
    int temp = n / 3 * 3;
    if(temp == n)return pow(3, n / 3);
    if(n - temp == 1)return pow(3, n / 3 - 1) * 4;
    return pow(3, n / 3) * 2;
}

www.sunshangyu.top

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值