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;
        }
    }
  • 相关阅读:
    教你怎么叠T恤
    最动人的情歌《The Power of Love》by Celine.Dion
    使代码简洁的 5 条忠告
    Timeout MessageBox
    内联函数
    局部对象
    const用法(转)
    心情
    内联函数
    局部对象
  • 原文地址:https://www.cnblogs.com/fisherinbox/p/5439377.html
Copyright © 2011-2022 走看看