Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ef3b04b

Browse files
authored
Create 0474-ones-and-zeroes.kt
1 parent b269084 commit ef3b04b

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

kotlin/0474-ones-and-zeroes.kt

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
* Recursion with memoization solution
3+
*/
4+
class Solution {
5+
fun findMaxForm(strs: Array<String>, m: Int, n: Int): Int {
6+
val dp = Array(m + 1){ Array(n + 1){ IntArray(strs.size){ -1 } } }
7+
8+
fun dfs(i: Int, m: Int, n: Int): Int {
9+
if(i == strs.size) return 0
10+
11+
if(dp[m][n][i] != -1) return dp[m][n][i]
12+
13+
val zeros = strs[i].count{ it == '0' }
14+
val ones = strs[i].count{ it == '1' }
15+
16+
dp[m][n][i] = dfs(i + 1, m, n)
17+
if(zeros <= m && ones <= n) {
18+
dp[m][n][i] = maxOf(
19+
dp[m][n][i],
20+
1 + dfs(i + 1, m - zeros, n - ones)
21+
)
22+
}
23+
24+
return dp[m][n][i]
25+
}
26+
27+
return dfs(0, m, n)
28+
}
29+
}
30+
31+
/*
32+
* DP solution
33+
*/
34+
class Solution {
35+
fun findMaxForm(strs: Array<String>, m: Int, n: Int): Int {
36+
val dp = Array(m + 1){ IntArray(n + 1) }
37+
38+
for(str in strs) {
39+
val zeros = str.count{ it == '0'}
40+
val ones = str.count{ it == '1'}
41+
for(i in m downTo zeros) {
42+
for(j in n downTo ones) {
43+
dp[i][j] = maxOf(
44+
1 + dp[i - zeros][j - ones],
45+
dp[i][j]
46+
)
47+
}
48+
}
49+
}
50+
51+
return dp[m][n]
52+
}
53+
}

0 commit comments

Comments
 (0)