Problem
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.
HintThere is a simple O(n) solution to this problem.
You may check the breaking results of n ranging from 7 to 10 to discover the regularities.
1. beat 40.83% O(log(n))
public class Solution { public int integerBreak(int n) { if (n < 4) return n-1; else if(n%3 == 0) return (int)Math.pow(3, n/3); else if(n%3 == 1) return 4*(int)Math.pow(3, (n-4)/3); else return 2*(int)Math.pow(3, n/3); } }
2. beat 40.83% O(n)
public class Solution { public int integerBreak(int n) { if (n<4) return n-1; int product = 1; while(n>4){ product*=3; n-=3; } return product*n; } }
3. DP beat 40.83% O(n)
public class Solution { public int integerBreak(int n) { if (n < 4) return n-1; int[] dp = new int[n+1]; dp[2] = 2; dp[3] = 3; for (int i = 4; i <= n; i++) { dp[i] = Math.max(3*dp[i-3], 2*dp[i-2]); } return dp[n]; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/66206.html
摘要:思路動態規劃,前五個數的最大乘積為,后面的第個數的最大乘積,由從后往前數包括本身的第三個數乘以得到。何睿何睿前個數的最大乘積動態規劃第個數的最大乘積為往前數第三個數思路與上面的思路一致,優化了空間源代碼文件在這里。 Description Given a positive integer n, break it into the sum of at least two positive...
摘要:題目要求將一個正整數分解為兩個或兩個以上的正整數,要求這些正整數的乘積最大。思路和代碼這里應用了一個數學的思路。假設我們有一個數字,該數組可以隨機分解為和。因此取時可以得到最好的結果。至于為什么我們需要盡可能用分解,因為。 題目要求 Given a positive integer n, break it into the sum of at least two positive in...
Problem A website domain like discuss.leetcode.com consists of various subdomains. At the top level, we have com, at the next level, we have leetcode.com, and at the lowest level, discuss.leetcode.com...
摘要:棧法復雜度時間空間思路逆波蘭表達式的計算十分方便,對于運算符,其運算的兩個數就是這個運算符前面的兩個數。注意對于減法,先彈出的是減號后面的數。 Evaluate Reverse Polish Notation Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operato...
Problem Implement function atoi to convert a string to an integer. If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values...
閱讀 1371·2021-09-30 09:55
閱讀 1897·2021-08-27 13:10
閱讀 2244·2019-08-29 17:22
閱讀 1298·2019-08-29 16:30
閱讀 3464·2019-08-26 18:37
閱讀 2348·2019-08-26 11:47
閱讀 1162·2019-08-23 14:44
閱讀 1740·2019-08-23 13:46