leetcode 343. Integer Break

来源:互联网 发布:php的curl扩展 编辑:程序博客网 时间:2024/06/18 10:52

写在前面

忙碌的一个月,很多事情也算是尘埃落定,各种安排也算是有条不紊。投了一篇icassp作为毕业的水文(结果未知)。科研方面,retargeting真的太难做了,跟导师商议后转到分割领域,目标暂时不定在科研,偏向工程实现,以coco比赛作为努力方向。游戏开发仍然是找工作的主要目标。leetcode 目前进入二刷,3个月时间二刷完成后再换平台。加油!

题目描述

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.

思路分析

客观来讲,本题是较容易想到的类型,抛开复杂的数学证明不谈,我们很容易想到的两数的乘积最大值发生在开方的附近,那么很显然,要得到继续分解的最大值,就需要对因子继续开方,而最终的开方结果一定是落在2或3的位置(整数),而2*2 < 3 *3,所以我们最终的题解就是找到足够多的3,此外,一种特殊的情况需要考虑,如果最后剩余的数是4,那么继续找3就会变成3+1而很明显3*1<4,所以如果剩余4,我们就不再处理。根据思路可以写出代码:

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