Inserting Operators (2)
InterviewTime limit2sMemory limit512 MB
Insert one of +, -, x, / between each adjacent pair from a limited supply, evaluating left to right with C++14 integer division, and report the largest and smallest results.
- Level
Medium6 of 10
- Topics
- Backtracking, Brute force, Implementation, Recursion
- Solved
- No attempts yet
Problem
You are given a sequence of numbers and a supply of operators to insert between adjacent numbers. The operators are addition (+), subtraction (-), multiplication (×) and division (÷) only, and the supply may hold more than of them. Exactly one operator goes between every pair of adjacent numbers, and you do not have to use every operator in the supply.
Putting one operator between each pair of numbers builds one expression. The order of the numbers stays as given.
If the sequence is 1, 2, 3, 4, 5, 6 and the supply is 3 additions, 2 subtractions, 1 multiplication and 1 division, there are 250 possible expressions. Six of them are:
An expression is evaluated from left to right, ignoring operator precedence. Division is integer division that keeps the quotient only, and a negative number divided by a positive number follows the C++14 rule: make the dividend positive, take the quotient, then flip the sign of that quotient back to negative. The six expressions above evaluate like this:
Given the numbers and the supply of operators, write a program that finds the largest and the smallest result over all expressions you can build.
Input
The first line contains the count of numbers . ()
The second line contains . ()
The third line contains four integers: the number of additions (+), subtractions (-), multiplications (×) and divisions (÷), in that order. Their sum is at least and at most .
Output
Print the largest result on the first line and the smallest result on the second line.
Only inputs where every expression evaluates to a value between -1000000000 and 1000000000 are given. Each intermediate value produced while evaluating from left to right also stays between -1000000000 and 1000000000.
Hint
When the sequence is 1, 2, 3, 4, 5, 6 and the supply is 3 additions, 2 subtractions, 1 multiplication and 1 division, the largest and the smallest results come from these two expressions.
- Largest:
- Smallest: