| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | | 3 | | // All Rights Reserved. |
| | | 4 | | // -------------------------------------------------------------------------------- |
| | | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | | 9 | | // known as Yevhenii Yeriemeieiv). |
| | | 10 | | // -------------------------------------------------------------------------------- |
| | | 11 | | |
| | | 12 | | namespace LeetCode.Algorithms.OnesAndZeroes; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class OnesAndZeroesDynamicProgramming : IOnesAndZeroes |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(l * m * n), where l is the length of strs |
| | | 19 | | /// Space complexity - O(m * n) |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="strs"></param> |
| | | 22 | | /// <param name="m"></param> |
| | | 23 | | /// <param name="n"></param> |
| | | 24 | | /// <returns></returns> |
| | | 25 | | public int FindMaxForm(string[] strs, int m, int n) |
| | 2 | 26 | | { |
| | 2 | 27 | | Span<int> dp = stackalloc int[(m + 1) * (n + 1)]; |
| | | 28 | | |
| | 22 | 29 | | foreach (var str in strs) |
| | 8 | 30 | | { |
| | 8 | 31 | | var zeros = 0; |
| | 8 | 32 | | var ones = 0; |
| | | 33 | | |
| | 60 | 34 | | foreach (var c in str) |
| | 18 | 35 | | { |
| | 18 | 36 | | if (c == '0') |
| | 9 | 37 | | { |
| | 9 | 38 | | zeros++; |
| | 9 | 39 | | } |
| | | 40 | | else |
| | 9 | 41 | | { |
| | 9 | 42 | | ones++; |
| | 9 | 43 | | } |
| | 18 | 44 | | } |
| | | 45 | | |
| | 70 | 46 | | for (var i = m; i >= zeros; i--) |
| | 27 | 47 | | { |
| | 188 | 48 | | for (var j = n; j >= ones; j--) |
| | 67 | 49 | | { |
| | 67 | 50 | | var index = GetIndex(i, j, n); |
| | 67 | 51 | | var previousIndex = GetIndex(i - zeros, j - ones, n); |
| | | 52 | | |
| | 67 | 53 | | dp[index] = Math.Max(dp[index], dp[previousIndex] + 1); |
| | 67 | 54 | | } |
| | 27 | 55 | | } |
| | 8 | 56 | | } |
| | | 57 | | |
| | 2 | 58 | | return dp[GetIndex(m, n, n)]; |
| | 2 | 59 | | } |
| | | 60 | | |
| | | 61 | | private static int GetIndex(int i, int j, int n) |
| | 136 | 62 | | { |
| | 136 | 63 | | return (i * (n + 1)) + j; |
| | 136 | 64 | | } |
| | | 65 | | } |