A dance with an aglorithm's complexity

偶尔善良 提交于 2019-12-07 06:56:28

Let there be n songs indexed 0..n-1. Let Opt(i) be the maximum total score given that we're free to dance starting on song i. The recurrence for Opt is

Opt(n) = 0
Opt(i) = max(Opt(i+1),
             Score(i) + Opt(i + 1 + Rest(i))) for i = 0..n-1.

Intuitively, we either don't dance song i and get the value of the remaining time, or we do, score song i, rest, and get the value of the time after resting.

This recurrence should be evaluated for i descending, with the previously calculated values cached in an array. The running time is O(n).

Recursion would be,

for i: 1 -> n
    DP(n) = max(0,(score(i)+DP(i+r)),DP(i+1)) 

where,

r = resting interval
0 is the situation where it is better not to dance at all :)

Edit 1: Adding explanation

Base case is participant doesn't dance so the total score will be 0

Otherwise, he either dances or not on a particular song. So the decision boils down to if he should dance on this song or not so that the ultimate score is maximized.

If he decided to dance, he will gain score(i) and cannot dance for rest(i) so the remaining max possible score will be the value of score(i) + DP(i + rest(i))

If he decides not to dance on this song, the score will be DP(i+1).

Because we want to maximize the score, we pick the max of these two values.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!