g0301_0400.s0343_integer_break.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0301_0400.s0343_integer_break;
// #Medium #Dynamic_Programming #Math #Algorithm_II_Day_18_Dynamic_Programming
// #Dynamic_Programming_I_Day_21 #2022_07_10_Time_0_ms_(100.00%)_Space_40.7_MB_(67.02%)
/**
* 343 - Integer Break\.
*
* Medium
*
* Given an integer `n`, break it into the sum of `k` **positive integers** , where `k >= 2`, and maximize the product of those integers.
*
* Return _the maximum product you can get_.
*
* **Example 1:**
*
* **Input:** n = 2
*
* **Output:** 1
*
* **Explanation:** 2 = 1 + 1, 1 × 1 = 1.
*
* **Example 2:**
*
* **Input:** n = 10
*
* **Output:** 36
*
* **Explanation:** 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
*
* **Constraints:**
*
* * `2 <= n <= 58`
**/
public class Solution {
private int[] arr;
public int integerBreak(int n) {
arr = new int[n + 1];
arr[2] = 1;
// only case involve with 1 other than 2 is 3
return n == 3 ? 2 : dp(n);
}
private int dp(int n) {
if (n <= 2) {
return arr[2];
} else if (arr[n] != 0) {
return arr[n];
} else {
int prod = 1;
for (int i = 2; i <= n; i++) {
prod = Math.max(prod, i * dp(n - i));
}
arr[n] = prod;
}
return arr[n];
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy