Algorithm categories ๐
Mathematics, strings, greedy algorithms, parsing.
Given an expression made up of positive integers and the + and - operators, write a program that places parentheses to minimize its value.
The expression is provided on the first line.
It consists of positive integers from
1 to
1000000 and the
+ and
- operators, with at least one operator.
The expression has a maximum length of
50.
Print the minimum possible result for the test case.
50-(50+40)-(30+20)-10 = 50 - 50 - 40 - 30 - 20 - 10 = -100
Problem explanation
Split the expression at each - to separate it into groups.
Always add the first group.
Treat each subsequent group as parenthesized: Split it at +, sum its numbers, and subtract the result.
Print the result after processing every group.
expression = input ().strip()
# 1. '-'๋ฅผ ๊ธฐ์ค์ผ๋ก ๋จผ์ ๋๋๋ค.
parts = expression.split( '-' )
# 2. ์ฒซ ๋ฒ์งธ ๋ฉ์ด๋ฆฌ๋ ๋ฌด์กฐ๊ฑด ๋ํ๋ค.
total = sum ( map ( int , parts[ 0 ].split( '+' )))
# 3. ๊ทธ ์ดํ ๋ฉ์ด๋ฆฌ๋ ๋ชจ๋ ๊ดํธ๋ก ๋ฌถ์ธ๋ค๊ณ ์๊ฐํ๊ณ ๊ฐ๊ฐ +๋ก ์ชผ๊ฐ์ ํฉ์ฐํ ๋ค ๋นผ๊ธฐ
for part in parts[ 1 :]:
total -= sum ( map ( int , part.split( '+' )))
print (total)
๐๏ธ
Do not copy this. Let's avoid writing code like this.
line = input ().strip().split( "-" )
answer = sum ( list ( map ( int , line[ 0 ].split( "+" ))))
print (answer if len (line) <= 1 else answer - sum ([ list ( map ( int , s.split( "-" )))[ 0 ] for s in "+" .join(line[ 1 :]).split( "+" )]))
To get the minimum value, group all numbers following the subtraction sign into parentheses and subtract them together.
only affects the sum inside a group.
marks the start of a group.
Think of everything after the first - as belonging inside ().
split('-') โ O(N).
split('+') for each group โ O(N) in total.
Converting each number with int() โ O(N).
Calculating the total โ O(N).
Overall time complexity: O(N).
Additional test cases, excluding the examples ๐
answer: -99
answer: -55
answer: -35
answer: -70
answer: -65
answer: -260
answer: -85
answer: 100