Skip to content

Commit d2f35bd

Browse files
authored
Add solution for maximizing partitions with bit manipulation
Implement a dynamic programming solution to maximize the number of partitions after operations on a string based on bit manipulation.
1 parent c79034c commit d2f35bd

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# Topics: Bit Manuputation, Bit-Mask, DP
2+
3+
4+
class Solution:
5+
def __init__(self):
6+
self.dp = {}
7+
8+
def countSetBits(self, n):
9+
count = 0
10+
while n > 0:
11+
count += n & 1
12+
n >>= 1
13+
return count
14+
15+
def helper(self, s, k, i, mask, isChange):
16+
n = len(s)
17+
if i == n:
18+
return 1
19+
20+
currState = (i << 27) | (mask << 1) | isChange
21+
22+
if currState in self.dp:
23+
return self.dp[currState]
24+
25+
result = 0
26+
val = ord(s[i]) - ord('a')
27+
28+
count = self.countSetBits(mask | (1 << val))
29+
temp = 0
30+
if count > k:
31+
temp = 1 + self.helper(s, k, i + 1, 1 << val, isChange)
32+
else:
33+
temp = self.helper(s, k, i + 1, mask | (1 << val), isChange)
34+
result = max(result, temp)
35+
36+
if isChange == 0:
37+
for j in range(26):
38+
count = self.countSetBits(mask | (1 << j))
39+
if count > k:
40+
temp = 1 + self.helper(s, k, i + 1, 1 << j, 1)
41+
else:
42+
temp = self.helper(s, k, i + 1, mask | (1 << j), 1)
43+
result = max(result, temp)
44+
45+
self.dp[currState] = result
46+
return result
47+
48+
def maxPartitionsAfterOperations(self, s, k):
49+
"""
50+
:type s: str
51+
:type k: int
52+
:rtype: int
53+
"""
54+
return self.helper(s, k, 0, 0, 0)
55+
56+
# Time Complexity: O(n × 2²⁷)
57+
# Auxiliary Space: O(n × 2²⁷)

0 commit comments

Comments
 (0)