14888-연산자끼워넣기
연산자를 끼워넣는 모든 순열을 얻는다.
모든 경우의 수에서의 결과값들을 얻는다.
결과값마다 최댓값과 최솟값을 업데이트 한다.
결과값이 음수가 나올 수 있으니 -int(1e9) 로 고려
from itertools import permutations
n = int(input())
nums = list(map(int,input().split()))
a,b,c,d = map(int,input().split())
cals = []
for i in range(a):
cals.append('+')
for i in range(b):
cals.append('-')
for i in range(c):
cals.append('*')
for i in range(d):
cals.append('//')
cal_cases = list(permutations(cals,len(cals)))
# print(cal_cases)
# 연산자 배치의 모든 경우
min_answer = int(1e9)
max_answer = -int(1e9)
for cal_case in cal_cases:
# cal_case = [+ + - * //]
# nums = [1,2,3,4,5,6]
num = nums[0]
for i in range(len(cal_case)):
if cal_case[i] == '+':
num += nums[i+1]
elif cal_case[i] == '-':
num -= nums[i + 1]
elif cal_case[i] == '*':
num *= nums[i + 1]
elif cal_case[i] == '//':
if num < 0:
num *= -1
num = num // nums[i+1]
num *= -1
else:
num = num // nums[i + 1]
min_answer = min(num, min_answer)
max_answer = max(num, max_answer)
print(max_answer)
print(min_answer)
Last updated
Was this helpful?