热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

leetcode343.IntegerBreak整数分割(c++)

Givenapositiveintegern,breakitintothesumofatleasttwopositiveintegersandmaximizethe

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 会报错~~本来不想写的
    }
};


推荐阅读
author-avatar
dreamingsue
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有