Given a sequence,say,
222
We have to put a ‘+’ or ‘* ‘ between each adjacent pair.
‘* ‘ has higher precedence over ‘+’
We have to o/p the string whose evaluation leads to minimum value.
O/p must be lexicographically smallest if there are more than one.
inp:222
o/p: 2*2+2
Explaination:
2+2+2=6
2+2*2=6
2*2+2=6
of this 3rd is lexicographically smallest.
I was wondering how to construct a DP solution for this.
Let
DP[N]be the smallest value we can obtain using the firstNelements. I will do a recursive implementation(using memoization) with pseudocode:Call it with
solve(0);You can easily reconstruct the solution after this. I haven’t tested it and maybe I have missed an edge case in the pseudocode but it should give you the right track.
P.S Sorry for the many edits.