Dynamic Programming Examples
1. Maximum Value Contiguous Subsequence
Problem: for an array A[1..n], find the maximum continguous subarray A[i:j] (where i=>0 and j <=n) such that the sum from i to j is greater than any other subarray of A[1..n]
​
​
-
def M(A,j):
-
V = [0] * (j+1)
-
V[0] = max(A[0],0)
-
-
for i in range(1,len(A),1):
-
V[i]= max(V[i-1]+A[i],A[i])
-
return max(V)
-
-
A = [0,1,2,3,-1,77,22,100,-44,-55]
-
j = len(A)
-
print M(A,j)
2. Making Change:
​
Solved. However, the solution conflicts with an existing homework problem.
​
3. Longest Increasing Subsequence
​
Problem: for an array A[1..n], find the longest subsequence (not necessarily contiguous) such that all elements in the subsequence are increasing from the previous.
​
​
-
def M(A):
-
V = [0]*(len(A)+1)
-
-
for i in range(0,len(A),1):
-
for j in range(0,i+1,1):
-
if (A[i] > A[j]):
-
V[i]=max(V[i],V[j]+1)
-
return max(V)
-
-
A = [1,2,44,3,5,100,220,6]
-
print M(A)
​
4. Integer Knapsack Problem (Duplicate Items Forbidden)
Problem: Given a knapsack of capacity=c and an array of items of sizes = S and an array of values=V, what is the optimal (highest value) solution of items that can be placed in the knapsack without exceeding the capacity.
​
-
def M(S,V,c):
-
C = [[0]*(c+1) for i in xrange(len(S)+1)]
-
for i in range(0,len(S),1):
-
for j in range(0,c+1,1):
-
if (i==0):
-
C[0][j]=max(V[0],0)
-
else:
-
if ((j-S[i]) >= 0):
-
C[i][j]=max(C[i-1][j],C[i-1][j-S[i]]+V[i])
-
else:
-
C[i][j]=max(C[i-1][j],V[i])
-
return C[len(S)-1][c]
-
-
S = [1,2,3,4,5]
-
V = [22,5,40,3,2]
-
c = 4
-
print M(S,V,c)
​
5. Edit Distance
​
Problem: Given two strings A[1..m], B[1..n], what are the minimum number of operations (delete, insert, replace) that can be performed on the strings to transform A into B.
​
-
def M(X,Y):
-
X = "!"+X # place a terminator character to ignore at front of string
-
Y = "!"+Y # place a terminator character to ignore at front of string
-
m = len(X)-1
-
n = len(Y)-1
-
T = [[float('inf')]*(len(Y)+1) for i in xrange(len(X)+1)]
-
-
for i in range(0,m,1):
-
for j in range(0,n,1):
-
if (i==0 or j==0):
-
T[i][j]=0
-
else:
-
if (X[i]!=Y[j]): val = T[i-1][j-1]+1
-
else: val = T[i-1][j-1]
-
T[i][j] = min(T[i-1][j]+1,T[i][j-1]+1,val)
-
return T[m-1][n-1]
-
-
X = "ALGOSCS505"
-
Y = "ALGORITHMS"
-
print M(X,Y)