File tree 1 file changed +42
-0
lines changed
1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * DP solution
3
+ */
4
+ class Solution {
5
+ fun integerBreak (n : Int ): Int {
6
+ val cache = IntArray (n + 1 ) {- 1 }
7
+
8
+ cache[1 ] = 1
9
+ for (num in 2 .. n) {
10
+ cache[num] = if (num == n) 0 else num
11
+ for (i in 1 .. num) {
12
+ val res = cache[i] * cache[num - i]
13
+ cache[num] = maxOf(cache[num], res)
14
+ }
15
+ }
16
+
17
+ return cache[n]
18
+ }
19
+ }
20
+
21
+ /*
22
+ * DFS + memoization solution
23
+ */
24
+ class Solution {
25
+ fun integerBreak (n : Int ): Int {
26
+ val cache = IntArray (n + 1 ) {- 1 }
27
+
28
+ fun dfs (num : Int ): Int {
29
+ if (cache[num] != - 1 ) return cache[num]
30
+
31
+ cache[num] = if (num == n) 0 else num
32
+ for (i in 1 until num) {
33
+ val res = dfs(i) * dfs(num - i)
34
+ cache[num] = maxOf(cache[num], res)
35
+ }
36
+
37
+ return cache[num]
38
+ }
39
+
40
+ return dfs(n)
41
+ }
42
+ }
You can’t perform that action at this time.
0 commit comments