Operator Signs
InterviewTime limit1sMemory limit1024 MB
Insert + or - between adjacent numbers so the left-to-right value equals the target, keeping every partial result within 10000, and print the lexicographically smallest expression.
- Level
Medium6 of 10
- Topics
- Dynamic programming, Backtracking, Greedy, Implementation
- Solved
- No attempts yet
Problem
You are given a sequence of positive integers and a positive target value. Insert a plus (+) or minus (-) sign between each pair of adjacent numbers so that, evaluating the expression from left to right, its value equals the target. The first number has no sign in front of it.
Input
The first line contains the length of the sequence (). The second line contains the members of the sequence separated by spaces. The third line contains the target value. Every member of the sequence and the target value are between and inclusive.
Output
Print, on a single line, the expression formed by keeping the numbers in the given order and inserting + or - signs between them (the first number has no leading sign). Consider only expressions in which the absolute value of every partial result (evaluated left to right) never exceeds ; at least one such expression is guaranteed to exist. Among all such expressions whose value equals the target, print the lexicographically smallest one (comparing the strings character by character, where + is considered smaller than -).