Skip to content

474. Ones and Zeroes 👍

  • Time: $O(kl \cdot mn)$, where $k = |\texttt{strs}|$ and $l = \max(|\texttt{strs[i]}|)$
  • Space: $O(mn)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  int findMaxForm(vector<string>& strs, int m, int n) {
    // dp[i][j] := the maximum size of the subset given i 0s and j 1s are
    // available
    vector<vector<int>> dp(m + 1, vector<int>(n + 1));

    for (const string& s : strs) {
      const int count0 = ranges::count(s, '0');
      const int count1 = s.length() - count0;
      for (int i = m; i >= count0; --i)
        for (int j = n; j >= count1; --j)
          dp[i][j] = max(dp[i][j], dp[i - count0][j - count1] + 1);
    }

    return dp[m][n];
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int findMaxForm(String[] strs, int m, int n) {
    // dp[i][j] := the maximum size of the subset given i 0s and j 1s are
    // available
    int[][] dp = new int[m + 1][n + 1];

    for (final String s : strs) {
      final int count0 = (int) s.chars().filter(c -> c == '0').count();
      final int count1 = (int) s.length() - count0;
      for (int i = m; i >= count0; --i)
        for (int j = n; j >= count1; --j)
          dp[i][j] = Math.max(dp[i][j], dp[i - count0][j - count1] + 1);
    }

    return dp[m][n];
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
    # dp[i][j] := the maximum size of the subset given i 0s and j 1s are
    # available
    dp = [[0] * (n + 1) for _ in range(m + 1)]

    for s in strs:
      count0 = s.count('0')
      count1 = len(s) - count0
      for i in range(m, count0 - 1, -1):
        for j in range(n, count1 - 1, -1):
          dp[i][j] = max(dp[i][j], dp[i - count0][j - count1] + 1)

    return dp[m][n]