Skip to content

Commit 40e7a58

Browse files
authored
Update 0343-integer-break.kt
1 parent 0ac8f44 commit 40e7a58

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

kotlin/0343-integer-break.kt

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* DP solution
2+
* DP solution O(n^2) time and space
33
*/
44
class Solution {
55
fun integerBreak(n: Int): Int {
@@ -19,7 +19,7 @@ class Solution {
1919
}
2020

2121
/*
22-
* DFS + memoization solution
22+
* DFS + memoization solution O(n^2) time and space
2323
*/
2424
class Solution {
2525
fun integerBreak(n: Int): Int {
@@ -40,3 +40,20 @@ class Solution {
4040
return dfs(n)
4141
}
4242
}
43+
44+
// Math solution O(n) time and O(1) space
45+
class Solution {
46+
fun integerBreak(n: Int): Int {
47+
if (n < 4) return n - 1
48+
49+
var res = 1
50+
var n2 = n
51+
while (n2 > 4) {
52+
res *= 3
53+
n2 -=3
54+
}
55+
56+
res *= n2
57+
return res
58+
}
59+
}

0 commit comments

Comments
 (0)