TGViewer
C# | LeetCode C# | LeetCode @easy_c_sharp_task · 3.18K subscribers
Post #1549 309
Задача: 474. Ones and Zeroes
Сложность: medium

Дан массив двоичных строк strs и два целых числа m и n.

Верните размер наибольшего подмножества strs, такого что в подмножестве содержится не более m нулей и n единиц.

Множество x является подмножеством множества y, если все элементы множества x также являются элементами множества y.

Пример:
Input: strs = ["10","0001","111001","1","0"], m = 5, n = 3
Output: 4
Explanation: The largest subset with at most 5 0's and 3 1's is {"10", "0001", "1", "0"}, so the answer is 4.
Other valid but smaller subsets include {"0001", "1"} and {"10", "1", "0"}.
{"111001"} is an invalid subset because it contains 4 1's, greater than the maximum of 3.


👨‍💻 Алгоритм:

1⃣Рассматриваем все возможные подмножества, прерывая цикл, если количество нулей превышает m или количество единиц превышает n.

2⃣Считаем количество нулей и единиц в каждом подмножестве.

3⃣Выбираем наибольшее подмножество, соответствующее условиям, и возвращаем его размер.

😎 Решение:
public class Solution {
public int FindMaxForm(string[] strs, int m, int n) {
int maxlen = 0;
for (int i = 0; i < (1 << strs.Length); i++) {
int zeroes = 0, ones = 0, len = 0;
for (int j = 0; j < 32; j++) {
if ((i & (1 << j)) != 0) {
int[] count = CountZeroesOnes(strs[j]);
zeroes += count[0];
ones += count[1];
if (zeroes > m || ones > n)
break;
len++;
}
}
if (zeroes <= m && ones <= n)
maxlen = Math.Max(maxlen, len);
}
return maxlen;
}

public int[] CountZeroesOnes(string s) {
int[] c = new int[2];
foreach (char ch in s) {
c[ch - '0']++;
}
return c;
}
}


Ставь 👍 и забирай 📚 Базу знаний
More from @easy_c_sharp_task
  1. Oct 15, 2026Задача: 759. Employee Free Time Сложность: hard Нам дан список schedule of employees, кото…
  2. Oct 14, 2026Задача: 583. Delete Operation for Two Strings Сложность: medium Даны две строки word1 и wo…
  3. Oct 14, 2026Задача: 1252. Cells with Odd Values in a Matrix Сложность: easy Имеется матрица m x n, кот…
  4. Oct 13, 2026Задача: 325. Maximum Size Subarray Sum Equals k Сложность: medium Дан целочисленный массив…
  5. Oct 13, 2026Задача: 1171. Remove Zero Sum Consecutive Nodes from Linked List Сложность: medium Дан ука…
  6. Oct 11, 2026Задача: 1061. Lexicographically Smallest Equivalent String Сложность: medium Даны две стро…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →