https://programmers.co.kr/learn/courses/30/lessons/67257
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from copy import deepcopy as copy
from itertools import permutations
import re
def solution(expression):
expression_ = expression
priority = ['+', '-', '*']
answer = 0
for ops in permutations(priority, len(priority)):
expression = copy(expression_)
for op in ops:
pattern = f'(\(-)?[\d]+\)?\{op}(\(-)?-?[\d]+\)?'
while selected := re.search(pattern, expression):
replaced = str(eval(selected.group()))
if int(replaced) < 0:
replaced = f"({replaced})"
expression = expression.replace(selected.group(), replaced)
answer = max(answer, abs(eval(expression)))
return answer
Complexity
$O(|\text{expression}|)$
PREVIOUSEtc