Online store~35 min2s · 256 MBtarget O(n) time, O(n) spacestacks
A shop app lets sellers write their own pricing formulas, such as max(3*(2+4),10)-min(8,5)/2. The formula uses whole numbers, the four operations, brackets, and the two functions min and max with two arguments.
You write the evaluator that the shop runs when a price is needed. The formulas are well formed, and the evaluator never has to report an error.
Write evaluate_formula(expression).
+, -, * and /, brackets, and calls min(a,b) and max(a,b) where a and b are formulas. There are no spaces.* and / bind more tightly than + and -. Operators of the same kind work from left to right. Brackets, and the arguments of min and max, are worked out first./ cuts the quotient towards zero: 7/2 is 3, and (0-7)/2 is -3.Input: expression = "max(3*(2+4),10)-min(8,5)/2"
Output: 16The table shows the order in which the parts are worked out.
| Step | What is worked out | Value |
|---|---|---|
| 1 | 3 * (2 + 4) | 18 |
| 2 | max(18, 10) | 18 |
| 3 | min(8, 5) | 5 |
| 4 | 5 / 2, cut towards zero | 2 |
| 5 | 18 - 2 | 16 |
The table lists the parts in the order they are worked out. Because / binds more tightly than -, the formula is 18 minus (5 / 2), and 5 / 2 is 2.
Input: expression = "7"
Output: 7A formula can be a single number.
Input: expression = "(2-5)/2"
Output: -1The bracket gives -3, and -3 / 2 is -1.5, which is cut towards zero to -1.
1 ≤ expression.length ≤ 1,000,000, with digits, + - * /, brackets, commas and the names min and maxWorking out the innermost brackets one at a time costs about n × g steps for g groups. Each value is written back into the text, so a million characters can cost 10^11 steps or more. A scan that keeps a stack of values and a stack of waiting operators reads each character once, and applies each operator once.