zoukankan      html  css  js  c++  java
  • 343. Integer Break -- Avota

    问题描述:

    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.

    解题思路:

    给定一个正整数n(其实后来测试发现n到了59其结果就超出int的表示范围了),将其拆解成至少两个正整数的和,计算拆解数的乘积,找出所能获得的最大乘积。这种输入某个数求取某种最好解的题目最简单有效的方法就是多列几个例子看看是否有规律,对于这题我们先列出4到12的结果看看:

    整数n 乘积最大对应的拆解(可能有多种) 最大乘积 模3
    4 2 * 2 4 1
    5 3 * 2 3*2 2
    6 3 * 3 3^2 0
    7 3 * 2 * 2 3*4 1
    8 3 * 3 * 2 3^2*2 2
    9 3 * 3 * 3 3^3 0
    10 3 * 3 * 2 * 2 3^2*4 1
    11 3 * 3 * 3 * 2 3^3*2 2
    12 3 * 3 * 3 * 3 3^4 0

    仔细观察拆解结果与n模3对应关系,发现余数为0时最大乘积为3的n/3次幂,余数为1时最大乘积为4乘以3的(n/3-1)次幂,余数为2时最大乘积为2乘以3的n/3次幂。

    示例代码:

    class Solution {
    public:
        int integerBreak(int n) {
            if(n == 2){
                return 1;
            }
            if(n == 3){
                return 2;
            }
            
            int k = n / 3;
            int yu = n - k * 3;
            int result = 0;
            
            if(yu == 1){
                result = 4 * pow(3, k-1);
            }
            else if(yu == 2){
                result = 2 * pow(3, k);
            }
            else{
                result = pow(3, k);
            }
            return result;
        }
    };
    
  • 相关阅读:
    PathInfo模式,thinkPHP模板与控制之间的关系
    thinkPHP无法显示验证码问题
    jQuery.validate 中文API手册
    MySQL 常用函数
    MySQL插入、更新与删除数据 习题
    MySQL查询语句练习题
    在windows下SphinxCoreseek的配置安装与测试
    Ubuntu上Coreseek+PHP的安装
    Ubuntu下安装CoreSeek
    Ubuntu更新命令
  • 原文地址:https://www.cnblogs.com/avota/p/5424493.html
Copyright © 2011-2022 走看看