Coin-row problem: There is a row of n coins whose values are some positive integers C0, C2, . . . , Cn-1, 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.
In the below code, n is the size of my array C(or number of coins), and this code returned the right result for the values [10, 2, 4, 6, 3, 9, 5] (the right result being 25). But when I run the same code for the values [3, 12, 10] or [3, 12, 10, 2], I got the wrong result. (The result should be 13 and 14 respectively for the set of values).
Please help me fix my code.
int max(int a, int b) {
if(a > b) return a;
return b;
}
int coin_row(int[] C, int n) {
if(n==1) return C[0];
if(n==2) return max(C[0],C[1];
int F[n], i;
F[0] = 0; F[1] = C[0];
for(i = 2;i < n;i++) {
F[i] = max(C[i] + F[i-2], F[i-1]);
}
return F[n-1];
}
F
stands for? IfF[i]
is maximum amount of money you can take using only firsti+1
coins, thenF[0] = 0; F[1] = C[0];
should be replaced withF[0] = C[0]; F[1] = max(C[0], C[1]);
just like in cases whenn
is 1 or 2. – fas