algorithm - An unparenthesized arithmetic expression -


an arithmetic expression can have many possible values

can me?

there dynamic programming solution.

for expression, can define "outmost split point" first operator not within parentheses. after split, if on +, need maximize left sub expression , right sub expression; if -, maximize left side , minimize right side.

you can use either dynamic programming or memoization implement algorithm. memoization straightforward: search each split point, , save answer in data structure (two 2d matrices, m[x][y] string max/min value of expression beginning @ x , ending @ y); when data in matrices, use instead of recompute.

use dynamic programming bit trickier, can think of way:

  1. first, loop through expression, finding max/min each consecutive 2 values operator between them (well, fancy way of saying compute it);
  2. loop through expression, finding max/min each consecutive 3 values operator between them (for a ? b ? c, computed assuming split point between a , b, , assuming split point on b , c, , store max/min values of these two);
  3. once know max/min k-length sequences, compute k + 1-length ones using same method in step 2, until k length of array, , return max value length k.

this same matrix chain multiplication algorithm, has o(n^3) complexity. complexity can proved crudely reasoning: need loop n - 1 times, each time @ n - 1 subsequences, , need try @ n - 1 split points. so, n ^ 3 time complexity.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -