Pick up coins for maximum gain
Picking_up_coins.cpp PickingUpCoins.javapublic static int pickUpCoins(List<Integer> C) {
int[][] T = new int[C.size()][C.size()];
for (int[] t : T) {
Arrays.fill(t, -1);
}
return pickUpCoinsHelper(C, 0, C.size() - 1, T);
}
private static int pickUpCoinsHelper(List<Integer> C, int a, int b,
int[][] T) {
if (a > b) {
return 0; // Base condition.
}
if (T[a][b] == -1) {
T[a][b] = Math.max(
C.get(a)
+ Math.min(pickUpCoinsHelper(C, a + 2, b, T),
pickUpCoinsHelper(C, a + 1, b - 1, T)),
C.get(b)
+ Math.min(pickUpCoinsHelper(C, a + 1, b - 1, T),
pickUpCoinsHelper(C, a, b - 2, T))
);
}
return T[a][b];
}