【leetcode】343. Integer Break

来源:互联网 发布:it外包公司怎么样 编辑:程序博客网 时间:2024/06/05 14:56

一、题目描述

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.

Hint:

  1. There is a simple O(n) solution to this problem.
  2. You may check the breaking results of n ranging from 7 to 10 to discover the regularities.


题目解读:给一个数n,n 的范围是在 [2, 58] 区间中,将n拆分成k (k大于等于2) 个数相加,使得这k个数的乘积最大,返回这个乘积


思路

找规律,根据提示将2~10这几个数的拆分写出来:

n=2 时, 2=1+1,result = 1

n=3时, 3=1+2, result = 2

n=4时, 4=2+2, result = 4

n=5时, 5=3+2, result = 6

n=6时, 6=3+3, result = 9

n=7时, 7=3+4, result = 12

n=8时, 8=3+3+2, result=18

n=9时, 9 = 3+3+3, result = 27

n=10时, 10 = 3+3+4, result=36

发现,只要尽多的拆分出3就能使得乘积最大,并且因子不能超过4,因为如果因子等于5,那么可以拆分成3+2的形式,因为3*2=6>5。


c++代码(0ms,17.24%)

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



0 0