arrays - At most k adjacent 1s (Maximum Value limited neighbors) -
in algorithms course, there's question in book goes follows: "you given array a[1..n] of positive numbers , integer k. have produce array b[1..n], such that: each j, b[j] either 1 or 0. array b has adjacent 1s @ k times. sum(a[j]*b[j]) 1 <= j <= n maximized." example given array [10, 100, 300, 400, 50, 4500, 200, 30, 90] , k = 2 array b can = [1, 0, 1, 1, 0, 1, 1, 0, 1] maximizes sum 5500.
the solution uses dynamic programing when discussing friends said recurrence relation of form m(i, j) = max(m(i-2, j) + a[i], m(i-1, j-1) + a[i])
can explain why so? or if have different form of solving such problem. find dynamic programing bit hard grasp. thank you.
m[i, j] max sum 1 i, j adjacent 1s
m[i,j] can computed max of 3 situations:
b[i]=0 => s=m[i-1, j] // a[i] not added sum, b[1..i-1] has same number of adjacent 1s (j) b[1..i] because b[i] 0 b[i]=1 , b[i-1]=0 => s=m[i-2, j]+a[i] // a[i] added sum, b[1..i-2] has same number of adjacencent 1s, because b[i-1] 0 b[i]=1 , b[i-1]=1 => s=m[i-1, j-1]+a[i] // a[i] added sum, since b[i] , b[i-1] both 1, count adjacent 1s, b[1..i-1] contains j-1 adjacent 1s
the recursive rule max of 3 sums above. end condition m[1, j]=a[1] because b[1..1] has 1 item b[1]=1 , no adjacent 1s.
the answer need m[n, k].
complexity o(nk).
Comments
Post a Comment