1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| public class Demo { private static int stole(int[] array) { int[][] dp = new int[3][array.length + 1]; for (int i = 0; i < dp.length; i++) { for (int j = 0; j < dp[0].length; j++) { dp[i][j] = -1; } } calculate(array, dp, 0, array.length); return dp[0][array.length]; }
private static int calculate(int[] array, int[][] dp, int front, int remaining) { if (remaining == 0) return 0; if (dp[front][remaining] != -1) return dp[front][remaining];
int left = -1; if (front < 2) { left = array[array.length - remaining] + calculate(array, dp, front + 1, remaining - 1); } int right = calculate(array, dp, 0, remaining - 1); dp[front][remaining] = Math.max(left, right); return dp[front][remaining]; }
public static void main(String[] args) { int[] arr = {1, 3, 5, 5, 10}; System.out.println(stole(arr)); } }
|