Skip to content

Commit b06b9d3

Browse files
committed
Time: 1557 ms (70.27%), Space: 18.2 MB (72.1%) - LeetHub
1 parent 41d776b commit b06b9d3

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# time complexity: O(l * m * n)
2+
# space complexity: O(l * m * n)
3+
from functools import cache
4+
from typing import List
5+
6+
7+
class Solution:
8+
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
9+
counter = [[s.count("0"), s.count("1")] for s in strs]
10+
11+
@cache
12+
def dp(i, j, idx):
13+
if i < 0 or j < 0:
14+
return float('-inf')
15+
16+
if idx == len(strs):
17+
return 0
18+
19+
return max(dp(i, j, idx+1), 1 + dp(i-counter[idx][0], j-counter[idx][1], idx+1))
20+
return dp(m, n, 0)
21+
22+
# time complexity: O(l * m * n)
23+
# space complexity: O(l * m * n)
24+
class Solution:
25+
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
26+
dp = [[0 for _ in range(n+1)] for _ in range(m+1)]
27+
counter = [[s.count("0"), s.count("1")] for s in strs]
28+
for zeroes, ones in counter:
29+
for i in range(m, zeroes-1, -1):
30+
for j in range(n, ones-1, -1):
31+
dp[i][j] = max(dp[i][j], 1+dp[i-zeroes][j-ones])
32+
return dp[-1][-1]
33+
34+
35+
strs = ["10", "0001", "111001", "1", "0"]
36+
m = 5
37+
n = 3
38+
print(Solution().findMaxForm(strs, m, n))
39+
strs = ["10", "0", "1"]
40+
m = 1
41+
n = 1
42+
print(Solution().findMaxForm(strs, m, n))

0 commit comments

Comments
 (0)