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;
        }
    }
  • 相关阅读:
    PHP大文件上传断点续传源码
    PHP大文件上传断点续传解决方案
    Flash大文件断点续传解决方案
    Flash大文件断点续传功能
    ASP.NET上传断点续传
    B/S文件上传下载解决方案
    web文件夹上传下载方案
    Codeforces 460E Roland and Rose(暴力)
    iOS_25_彩票骨架搭建+导航栏适配
    配置Redmine的邮件通知功能
  • 原文地址:https://www.cnblogs.com/fisherinbox/p/5439377.html
Copyright © 2011-2022 走看看