Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Latihan Soal DP
Coin-row problem
• There is a row of n coins whose values are some positive integers c1,
c2, . . . , cn, not necessarily distinct. The goal is to pick up the
maximum amount of money subject to the constraint that no two
coins adjacent in the initial row can be picked up.
• Example:
• Coin = [5, 1, 2, 10, 6, 2] ans = 17
• Coin = [5, 1, 2, 10, 6] ans = 15
1. Perhitungan Manual
2. Recurrence overlapping sub-problem
• 𝐹 𝑛 = max 𝐶 𝑛 + 𝐹 𝑛 − 2 , 𝐹 𝑛 − 1
• Base case:
• F[0] = 0
• F[1] = C[1]
• Recursive case:
• max 𝐶 𝑛 + 𝐹 𝑛 − 2 , 𝐹 𝑛 − 1
3. Pseudocode Recursive (1)
// total == len + 1
Coin-Row-Rec(R, len)
1. if (len == 0)
2. return 0
3. if len == 0
4. return R[1]
5. else
6. R[len] = max(R[len] + Coin-Row-Rec(R, len-2), Coin-Row-Rec(R,
len-1))
7. if (len == total)
8. return R[len]
9. else
10. return 0
3. Pseudocode Recursive (2)
CoinRow(i, P)
1. nilai = -9999
2. for i to 6
3. nilai = max(nilai, P[i] + CoinRow(i+2, P)
4. return nilai