-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0343-integer-break.kt
78 lines (64 loc) · 1.58 KB
/
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
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
70
71
72
73
74
75
76
77
78
/*
* DP solution O(n^2) time and space
*/
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 O(n^2) time and space
*/
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)
}
}
// Math solution O(n) time and O(1) space
class Solution {
fun integerBreak(n: Int): Int {
if (n < 4) return n - 1
var res = 1
var n2 = n
while (n2 > 4) {
res *= 3
n2 -=3
}
res *= n2
return res
}
}
// Mathimatically solved O(1)
class Solution {
fun integerBreak(n: Int): Int {
if (n < 4) return n - 1
var res = n / 3
var rem = n % 3
if (rem == 1) {
rem = 4
res--
} else if (rem == 0) {
rem = 1
}
return (Math.pow(3.toDouble(), res.toDouble()) * rem).toInt()
}
}