forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0474-ones-and-zeroes.kt
53 lines (44 loc) · 1.32 KB
/
0474-ones-and-zeroes.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
/*
* Recursion with memoization solution
*/
class Solution {
fun findMaxForm(strs: Array<String>, m: Int, n: Int): Int {
val dp = Array(m + 1){ Array(n + 1){ IntArray(strs.size){ -1 } } }
fun dfs(i: Int, m: Int, n: Int): Int {
if(i == strs.size) return 0
if(dp[m][n][i] != -1) return dp[m][n][i]
val zeros = strs[i].count{ it == '0' }
val ones = strs[i].count{ it == '1' }
dp[m][n][i] = dfs(i + 1, m, n)
if(zeros <= m && ones <= n) {
dp[m][n][i] = maxOf(
dp[m][n][i],
1 + dfs(i + 1, m - zeros, n - ones)
)
}
return dp[m][n][i]
}
return dfs(0, m, n)
}
}
/*
* DP solution
*/
class Solution {
fun findMaxForm(strs: Array<String>, m: Int, n: Int): Int {
val dp = Array(m + 1){ IntArray(n + 1) }
for(str in strs) {
val zeros = str.count{ it == '0'}
val ones = str.count{ it == '1'}
for(i in m downTo zeros) {
for(j in n downTo ones) {
dp[i][j] = maxOf(
1 + dp[i - zeros][j - ones],
dp[i][j]
)
}
}
}
return dp[m][n]
}
}