forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOnesAndZeros.java
106 lines (78 loc) · 2.37 KB
/
OnesAndZeros.java
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// Solution 2
class Solution {
// TC : O(n*m*len)
// SC : O(n*m)
public int findMaxForm(String[] strs, int m, int n) {
int[][] strFreq = new int[strs.length][2];
int i = 0;
for (String str : strs) {
strFreq[i] = freqCount(str);
i++;
}
int[][] dp = new int[m + 1][n + 1];
for (i = 0; i < strs.length; i++) {
int oneFreq = strFreq[i][1];
int zeroFreq = strFreq[i][0];
for (int k = m; k >= zeroFreq; k--) {
for (int j = n; j >= oneFreq; j--) {
dp[k][j] = Math.max(dp[k][j], dp[k - zeroFreq][j - oneFreq] + 1);
}
}
}
return dp[m][n];
}
private int[] freqCount(String str) {
int[] freq = new int[2];
for (char a : str.toCharArray()) {
if (a == '0') {
freq[0]++;
} else {
freq[1]++;
}
}
return freq;
}
}
// Solution 1
class Solution {
int[][][] dp = null;
public int findMaxForm(String[] strs, int m, int n) {
dp = new int[m + 1][n + 1][strs.length];
int[][] strFreq = new int[strs.length][2];
int i = 0;
for (String str : strs) {
strFreq[i] = freqCount(str);
i++;
}
return helper(strs, m, n, 0, strFreq);
}
private int helper(String[] strs, int m, int n, int index, int[][] strFreq) {
if (index >= strs.length || (m + n) <= 0) {
return 0;
}
if (dp[m][n][index] > 0) {
return dp[m][n][index];
}
int countElIfCurrInc = 0;
int countElIfCurrExc = 0;
int zeroFreq = strFreq[index][0];
int oneFreq = strFreq[index][1];
if (m >= zeroFreq && n >= oneFreq) {
countElIfCurrInc = 1 + helper(strs, m - zeroFreq, n - oneFreq, index + 1, strFreq);
}
countElIfCurrExc = helper(strs, m, n, index + 1, strFreq);
dp[m][n][index] = Math.max(countElIfCurrInc, countElIfCurrExc);
return dp[m][n][index];
}
private int[] freqCount(String str) {
int[] freq = new int[2];
for (char a : str.toCharArray()) {
if (a == '0') {
freq[0]++;
} else {
freq[1]++;
}
}
return freq;
}
}