Untitled
unknown
plain_text
9 months ago
1.5 kB
6
Indexable
import java.util.Arrays;
public class Solution {
public int findMaxForm(String[] strs, int m, int n) {
// Create a memoization table
int[][][] memo = new int[strs.length][m + 1][n + 1];
for (int[][] matrix : memo) {
for (int[] row : matrix) {
Arrays.fill(row, -1);
}
}
return dfs(strs, 0, m, n, memo);
}
private int dfs(String[] strs, int index, int m, int n, int[][][] memo) {
// Base cases
if (index == strs.length) {
return 0;
}
if (m < 0 || n < 0) {
return Integer.MIN_VALUE; // Invalid state
}
// If already computed, return the cached result
if (memo[index][m][n] != -1) {
return memo[index][m][n];
}
// Count zeros and ones in the current string
int zeros = 0, ones = 0;
for (char c : strs[index].toCharArray()) {
if (c == '0') zeros++;
else ones++;
}
// Choice 1: Skip the current string
int skip = dfs(strs, index + 1, m, n, memo);
// Choice 2: Include the current string
int include = Integer.MIN_VALUE;
if (m >= zeros && n >= ones) {
include = 1 + dfs(strs, index + 1, m - zeros, n - ones, memo);
}
// Store the result in memo and return the maximum of the two choices
memo[index][m][n] = Math.max(skip, include);
return memo[index][m][n];
}
}
Editor is loading...
Leave a Comment