Integer Break Solutions in Java
Number 343
Difficulty Medium
Acceptance 50.4%
Link LeetCode
Solutions
Java solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/integer-break/description//// Author : liuyubobobo/// Time : 2017-11-19import java.util.Arrays;/// Memory Search/// Time Complexity: O(n^2)/// Space Complexity: O(n)public class Solution1 {private int[] memo;public int integerBreak(int n) {if(n < 1)throw new IllegalArgumentException("n should be greater than zero");memo = new int[n+1];Arrays.fill(memo, -1);return breakInteger(n);}private int breakInteger(int n){if(n == 1)return 1;if(memo[n] != -1)return memo[n];int res = -1;for(int i = 1 ; i <= n - 1 ; i ++)res = max3(res, i * (n - i) , i * breakInteger(n - i));memo[n] = res;return res;}private int max3(int a, int b, int c){return Math.max(a, Math.max(b, c));}public static void main(String[] args) {System.out.println((new Solution1()).integerBreak(2));System.out.println((new Solution1()).integerBreak(10));}}
Java solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/integer-break/description//// Author : liuyubobobo/// Time : 2017-11-19/// Dynamic Programming/// Time Complexity: O(n^2)/// Space Complexity: O(n)public class Solution2 {public int integerBreak(int n) {if(n < 1)throw new IllegalArgumentException("n should be greater than zero");int[] memo = new int[n+1];memo[1] = 1;for(int i = 2 ; i <= n ; i ++)for(int j = 1 ; j <= i - 1 ; j ++)memo[i] = max3(memo[i], j * (i - j), j * memo[i - j]);return memo[n];}private int max3(int a, int b, int c){return Math.max(a, Math.max(b, c));}public static void main(String[] args) {System.out.println((new Solution2()).integerBreak(2));System.out.println((new Solution2()).integerBreak(10));}}
Java solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/integer-break/description//// Author : liuyubobobo/// Time : 2019-07-24/// Dynamic Programming/// Deal with 2, 3 and 4 seperately/// Time Complexity: O(n^2)/// Space Complexity: O(n)public class Solution3 {public int integerBreak(int n) {if(n < 1)throw new IllegalArgumentException("n should be greater than zero");if(n == 2) return 1;if(n == 3) return 2;int[] memo = new int[n+1];memo[1] = 1;memo[2] = 2;memo[3] = 3;for(int i = 2 ; i <= n ; i ++)for(int j = 1 ; j <= i / 2 ; j ++)memo[i] = Math.max(memo[i], memo[j] * memo[i - j]);return memo[n];}public static void main(String[] args) {System.out.println((new Solution2()).integerBreak(2));System.out.println((new Solution2()).integerBreak(10));}}