We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent ebebd81 commit 3758283Copy full SHA for 3758283
1 file changed
kotlin/0343-integer-break.kt
@@ -0,0 +1,42 @@
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
25
26
27
28
+ fun dfs(num: Int): Int {
29
+ if (cache[num] != -1) return cache[num]
30
31
32
+ for (i in 1 until num) {
33
+ val res = dfs(i) * dfs(num - i)
34
35
36
37
+ return cache[num]
38
39
40
+ return dfs(n)
41
42
0 commit comments