[leetcode] 343. Integer Break 解题报告

来源:互联网 发布:游戏作弊神器软件 编辑:程序博客网 时间:2024/05/21 15:47

题目链接: https://leetcode.com/problems/integer-break/

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.


思路:

2 = 1+1

3 = 1+2

4 = 2+2

5 = 2+3

6 = 3+3

7 = 3+4

8 = 3+3+2

9 = 3+3+3

10 = 3+3+4

11 = 3+3+3+2

12 = 3+3+3+3

可以看出如果n>4那么n可以一直取3直到n<=4, 这样的乘积最大.

代码如下:

class Solution {public:    int integerBreak(int n) {        if(n==2) return 1;        if(n==3) return 2;        int sum = 1;        while(n > 4)        {            sum*=3;            n -= 3;        }        sum *= n;        return sum;    }};


0 0
原创粉丝点击