Skip to content

Commit b43b827

Browse files
authored
Update minimum-cost-to-change-the-final-value-of-expression.py
1 parent a79246a commit b43b827

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Python/minimum-cost-to-change-the-final-value-of-expression.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,44 @@
22
# Space: O(n)
33

44
class Solution(object):
5+
def minOperationsToFlip(self, expression):
6+
"""
7+
:type expression: str
8+
:rtype: int
9+
"""
10+
def compute(operands, operators):
11+
right, left, op = operands.pop(), operands.pop(), operators.pop()
12+
if op == '&':
13+
operands.append([min(left[0], right[0]),
14+
min(left[1]+right[1], min(left[1], right[1])+1)])
15+
else:
16+
operands.append([min(left[0]+right[0], min(left[0], right[0])+1),
17+
min(left[1], right[1])])
18+
19+
precedence = {'&':0, '|':0}
20+
operands, operators = [], []
21+
for c in expression:
22+
if c.isdigit():
23+
operands.append([int(c != '0'), int(c != '1')])
24+
elif c == '(':
25+
operators.append(c)
26+
elif c == ')':
27+
while operators[-1] != '(':
28+
compute(operands, operators)
29+
operators.pop()
30+
elif c in precedence:
31+
while operators and operators[-1] in precedence and \
32+
precedence[operators[-1]] >= precedence[c]:
33+
compute(operands, operators)
34+
operators.append(c)
35+
while operators:
36+
compute(operands, operators)
37+
return max(operands[-1])
38+
39+
40+
# Time: O(n)
41+
# Space: O(n)
42+
class Solution2(object):
543
def minOperationsToFlip(self, expression):
644
"""
745
:type expression: str

0 commit comments

Comments
 (0)