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:
- first, loop through expression, finding max/min each consecutive 2 values operator between them (well, fancy way of saying compute it);
- loop through expression, finding max/min each consecutive 3 values operator between them (for
a ? b ? c
, computed assuming split point betweena
,b
, , assuming split point onb
,c
, , store max/min values of these two); - once know max/min
k
-length sequences, computek + 1
-length ones using same method in step 2, until k length of array, , return max value lengthk
.
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
Post a Comment