forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0343-integer-break.kt
42 lines (35 loc) · 905 Bytes
/
0343-integer-break.kt
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
/*
* DP solution
*/
class Solution {
fun integerBreak(n: Int): Int {
val cache = IntArray(n + 1) {-1}
cache[1] = 1
for (num in 2..n) {
cache[num] = if (num == n) 0 else num
for (i in 1..num) {
val res = cache[i] * cache[num - i]
cache[num] = maxOf(cache[num], res)
}
}
return cache[n]
}
}
/*
* DFS + memoization solution
*/
class Solution {
fun integerBreak(n: Int): Int {
val cache = IntArray(n + 1) {-1}
fun dfs(num: Int): Int {
if (cache[num] != -1) return cache[num]
cache[num] = if (num == n) 0 else num
for (i in 1 until num) {
val res = dfs(i) * dfs(num - i)
cache[num] = maxOf(cache[num], res)
}
return cache[num]
}
return dfs(n)
}
}