-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path343.integer-break.java
More file actions
69 lines (63 loc) · 1.42 KB
/
Copy path343.integer-break.java
File metadata and controls
69 lines (63 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
* @lc app=leetcode id=343 lang=java
*
* [343] Integer Break
*
* https://leetcode.com/problems/integer-break/description/
*
* algorithms
* Medium (47.85%)
* Total Accepted: 80.1K
* Total Submissions: 167.3K
* Testcase Example: '2'
*
* 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.
*
* Example 1:
*
*
*
* Input: 2
* Output: 1
* Explanation: 2 = 1 + 1, 1 × 1 = 1.
*
*
* Example 2:
*
*
* Input: 10
* Output: 36
* Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
*
* Note: You may assume that n is not less than 2 and not larger than 58.
*
*
*/
class Solution {
public int integerBreak(int n) {
if (n == 1) {
return 1;
}
int[] dp = new int[n + 1];
return helper(dp, n);
}
private int helper(int[] dp, int n) {
if (n <= 1) {
return 1;
}
if (dp[n] > 0) {
return dp[n];
}
int max = 0;
for (int i = 1; i < n; i++) {
max = Math.max(max, i * (n - i));
max = Math.max(max, helper(dp, i) * (n - i));
max = Math.max(max, i * helper(dp, n - i));
max = Math.max(max, helper(dp, i) * helper(dp, n - i));
}
dp[n] = max;
return max;
}
}