Leetcode | Integer Break

来源:互联网 发布:中世纪2王国战役优化9 编辑:程序博客网 时间:2024/06/03 21:10

原题链接: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 and not larger than 58.

题目大概意思就是给定一个整数n,然后把它分解成至少2个数的和,然后这些分解后的数字的积要达到最大,最后输出这个最大积。

这道题刚着手去想时,会觉得有点复杂,因为把它分解成至少两个数的情况太多了,根本就不可能全部列举出来,但仔细思考后会发现,只要把它分解成2或者3这些数的和,它们的积就会达到最大值,所以这道题就变得很简单了,只需要O(n)就能解决。


以下为源代码:

class Solution {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;    }};
原创粉丝点击