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;
        }
    }
  • 相关阅读:
    CSS3属性transform详解之(旋转:rotate,缩放:scale,倾斜:skew,移动:translate)
    MySQL<添加、更新与删除数据>
    MySQL<数据库和表的基本操作>
    MySQL<数据库入门>
    MySql阶段案例
    Mysql综合案例
    Mysql课后思考题
    Java课后思考题
    Java课后简答题
    超全面的JavaWeb笔记day23<AJAX>
  • 原文地址:https://www.cnblogs.com/fisherinbox/p/5439377.html
Copyright © 2011-2022 走看看