LeetCode 343. Integer Break

来源:互联网 发布:淘宝网夏装新款女装 编辑:程序博客网 时间:2024/06/06 08:56

343. Integer Break

Description
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).

Analysis
这道题的意思是将一个拆分,返回其拆分后的每个数乘起来的最大乘积。
一开始这道题其实并没有思路。
后来发现,其实应该先将每一个数拆分成足够多的3。
下面进行说明:
2 = 1+1 返回1*1=1
3 = 1+2 返回1*2=2
4 = 2+2 返回2*2=4
5 = 3+2 返回2*3 =6
6 = 3+3 返回3*3 =9
7 = 3+4 返回3*4 =12
8 = 3+3+2 返回3*3*2 =18
9 = 3+3+3 返回3*3*3 =27
10 = 3+3+4 返回3*3*4 =36

不难得到 4不能再分解,因为4分解后依然得到4,而1,2,3再分解得到的都是比自己小的值。
从上述式子不难得到应该先将每个数拆分成成3,当数小于等于4时停止拆分。

Code

class Solution {public:    int integerBreak(int n) {        int res =1;        if(n ==2) return 1;        if(n ==3) return 2;        while(n>4){            res *=3;            n-=3;        }        return res*n;    }};
0 0
原创粉丝点击