zoukankan      html  css  js  c++  java
  • Leetcode 343 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.

    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.

    思路:一开始想的是递归,但是超时了。后来看了hint,发现了规律,如下可以看出:

    4    4
    5    3*2
    6    3*3
    7    3*4
    8    3*3*2
    9    3*3*3
    10    3*3*4
    11    3*3*3*2
    12    3*3*3*3
    13    3*3*3*4

    public class S343 {
        public int integerBreak(int n) {
            //LTE
    /*        int max = 0;
            if (n == 2) {
                return 1;
            }
            if (n == 3) {
                return 2;
            }
            for (int i = 2;i <= n/2;i++) {
                int temp = Math.max(i, integerBreak(i))* Math.max(n-i,integerBreak(n-i));
                if (temp > max)
                    max = temp;
            }
            return max;*/
            //有规律可循
            /*
            4     4
            5     3*2
            6     3*3
            7     3*4
            8     3*3*2
            9     3*3*3
            10    3*3*4
            11    3*3*3*2
            12    3*3*3*3
            13    3*3*3*4
            */
            if (n == 2) {
                return 1;
            }
            if (n == 3) {
                return 2;
            }
            int i = (n-4)/3;
            int ret = 0;
            if ((n-4)%3 == 0) {
                ret = 4*(int)Math.pow(3, i);
            } else if ((n-4)%3 == 1) {
                ret = 2*(int)Math.pow(3, i+1);
            } else {
                ret = (int)Math.pow(3, i+2);
            }
            return ret;
        }
    }
  • 相关阅读:
    go引入包一直是红色,没有引入的解决办法
    php 把抛出错误记录到日志中
    亚马逊查询接口
    git 合并指定文件到另一个分支
    content-type
    Echarts(饼图Pie)
    DIN 模型速记
    DeepFM 要点速记
    youtube DNN 模型要点速记
    java设计模式之迭代器
  • 原文地址:https://www.cnblogs.com/fisherinbox/p/5439377.html
Copyright © 2011-2022 走看看