前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode 343. Integer Break

leetcode 343. Integer Break

作者头像
眯眯眼的猫头鹰
发布2018-10-31 11:19:59
2350
发布2018-10-31 11:19:59
举报

题目要求

代码语言:javascript
复制
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).

Note: You may assume that n is not less than 2 and not larger than 58.

将一个正整数分解为两个或两个以上的正整数,要求这些正整数的乘积最大。

思路和代码

这里应用了一个数学的思路。假设我们有一个数字n,该数组可以随机分解为t和n-t。当分解为n/2时可以获得最大的乘积。因此t取n/2时可以得到最好的结果。但是这里我们明显还可以继续对t分解(如果t大于1),这样逐个分解之后终归会分解为2或者1为质因数

假设N为偶数,(N/2)*(N/2)>=N, 则 N>=4 假设N为奇数,(N-1)/2 *(N+1)/2, 则 N>=5

因此分解的数小于4。

至于为什么我们需要尽可能用3分解,因为3*3>2*2*2

代码语言:javascript
复制
    public int integerBreak(int n) {
        if(n == 2) return 1;
        if(n == 3) return 2;
        
        int product = 1;
        while(n >4){
            product *= 3;
            n -= 3;
        }
        
        product *= n;
        return product;
    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目要求
  • 思路和代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档