leetcode 343.Integer Break 整数分割(c++)

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.

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,分割这个数成几个正整数数之和(至少2个正整数),并且使这些数乘积最大。返回你可以得到的最大乘积。

例如,给定n=2,返回1(2=1+1); 给定n=10,返回36(10=3+3+4)。

注意:你可以假设n不小于2.

提示:1.这个题目存在O(n)的解法;

  2.你可以检测7-10范围内的数来发现规律。

解答思路:先找规律咯~~~  按题目说的,7=3+4,8=3+3+2,9=3+3+3,10=3+3+4。看出来了吗?当一个数分成最接近N个3时,结果最大,即N%3=0,则全是3,N%3=1,最后一个为4,N%3=2,最后一个为2.知道规律,答案就简单了~可AC的C++代码如下:

class Solution {
public:
    int integerBreak(int n) {
        if(n<2)     return 0;
        if(n==2)    return 1;
        if(n==3)    return 2;
        if(n%3==0)  return pow(3,n/3);
        if(n%3==1)  return 4*pow(3,n/3-1);
        if(n%3==2)  return 2*pow(3,n/3);
        return 0;//没有这个return 0 会报错~~本来不想写的
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值