




Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Dynamic programming and memoization techniques used to maximize the sum in a choosing game and find the length of the longest common subsequence between two strings. Lecture notes, examples, and code snippets in java. Dynamic programming is a method for solving complex problems by breaking them down into simpler subproblems and solving each subproblem only once, while memoization is a technique for storing and reusing the results of expensive function calls to avoid redundant computation.
Typology: Slides
1 / 8
This page cannot be seen from the preview
Don't miss anything!





int bestSum (int[] V, int left, int right, int total, int[][] memo) { if (left > right) return 0; else if (memo[left][right] == -1) { int L = V[left] + total - bestSum (V, left+1, right, total-V[left],memo); int R = V[right] + total - bestSum (V, left, right-1, total-V[right],memo); memo[left][right] = Math.max (L, R); } return memo[left][right]; } }
int bestSum (int[] V) { int[][] memo = new int[V.length][V.length]; int[][] total = new int[V.length][V.length]; for (int i = 0; i < V.length; i += 1) memo[i][i] = total[i][i] = V[i]; for (int k = 1; k < V.length; k += 1) for (int i = 0; i < V.length-k-1; i += 1) { total[i][i+k] = V[i] + total[i+1][i+k]; int L = V[i] + total[i+1][i+k] - memo[i+1][i+k]; int R = V[i+k] + total[i][i+k-1] - memo[i][i+k-1]; memo[i][i+k] = Math.max (L, R); } return memo[0][V.length-1]; }
/** Length of longest common subsequence of S0[0..k0-1]
private static int lls (String S0, int k0, String S1, int k1, int[][] memo) { if (k0 == 0 || k1 == 0) return 0; if (memo[k0][k1] == -1) { if (S0[k0-1] == S1[k1-1]) memo[k0][k1] = 1 + lls (S0, k0-1, S1, k1-1, memo); else memo[k0][k1] = Math.max (lls (S0, k0-1, S1, k1, memo), lls (S0, k0, S1, k1-1, memo)); } return memo[k0][k1]; }
/** Length of longest common subsequence of S0[0..k0-1]
private static int lls (String S0, int k0, String S1, int k1, int[][] memo) { if (k0 == 0 || k1 == 0) return 0; if (memo[k0][k1] == -1) { if (S0[k0-1] == S1[k1-1]) memo[k0][k1] = 1 + lls (S0, k0-1, S1, k1-1, memo); else memo[k0][k1] = Math.max (lls (S0, k0-1, S1, k1, memo), lls (S0, k0, S1, k1-1, memo)); } return memo[k0][k1]; }