Place the given +, -, *, / operators between N numbers to form an expression, then report the largest and smallest values it can take.
Medium6Brute forceBacktrackingImplementationMathNo attempts yetTime limit2sMemory limit512 MBYou are given a sequence of N numbers A1,A2,…,AN, together with N−1 operators to insert between the numbers. The operators are addition (+), subtraction (−), multiplication (×) and division (÷), and nothing else.
Put one operator into each gap between two neighboring numbers to build a single expression. The order of the given numbers must not change.
For example, if the sequence is 1, 2, 3, 4, 5, 6 and the given operators are two additions, one subtraction, one multiplication and one division, there are 60 expressions in total. Four of them are:
An expression is evaluated by operator precedence. × and ÷ come before + and −, and operators of equal precedence are applied from left to right. Division is integer division that keeps only the quotient. Under these rules the four expressions above evaluate to:
Given N numbers and N−1 operators, write a program that finds the largest and the smallest value an expression can take.
The first line contains the count of numbers N (2≤N≤11). The second line contains A1,A2,…,AN (1≤Ai≤100). The third line contains four integers whose sum is N−1: the number of additions, subtractions, multiplications and divisions, in that order.
Print the largest value an expression can take on the first line, and the smallest value on the second line. Only inputs whose largest and smallest values are at least -1,000,000,000 and at most 1,000,000,000 are given. Every value computed along the way is also at least -1,000,000,000 and at most 1,000,000,000, in whatever order the expression is evaluated.
For the input where the sequence is 1, 2, 3, 4, 5, 6 and the operators are two additions, one subtraction, one multiplication and one division, these two expressions give the largest and the smallest value.