Algorithm to bracket an expression in order to maximize its value

后端 未结 1 518
伪装坚强ぢ
伪装坚强ぢ 2021-01-04 22:08

I found this while looking up problems on dynamic programming. You are given an unparanthesized expression of the form V0 O0 V1 O1 .... Vn-1

We have to put brackets

相关标签:
1条回答
  • 2021-01-04 22:44

    It is easier to analyze calculation of A[i,j] elements from shorter ranges to longer ranges. Algorithm for that looks like:

    # Initialization of single values
    for i in 0, ..., n-1:
      A[i,i] = V[i]
    
    # Iterate through number of operation
    for d in 1, ..., n-1:
      # Range start
      for i in 0, ..., n-1-d:
        j = i + d
        A[i,j] = max( A[i,x] O_x A[x+1,j] for x in i, ..., j-1)
    
    print 'Result', A[0,n-1]
    

    Since A[] can be implemented with constant time access (array) than algorithm is O(n^3).

    0 讨论(0)
提交回复
热议问题