Created
November 5, 2015 18:34
-
-
Save ashwath10110/6d29ed840f076e260ade to your computer and use it in GitHub Desktop.
Dynamic Programming funtions Using bottom up approach C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static int[] p = { 1, 5, 8, 9, 10, 17, 17, 20 }; | |
static int N = p.Length; | |
static int[,] cache = new int[N, N]; | |
static int[] mem = new int[N + 1]; | |
public static int Max(int a, int b) | |
{ | |
return a > b ? a : b; | |
} | |
public static int Min(int a, int b) | |
{ | |
return a < b ? a : b; | |
} | |
public static int EditDistance(ref int[,] dp, String S1, String S2, int m, int n) | |
{ | |
if (m == 0) | |
{ | |
dp[m, n] = n; | |
return dp[m, n]; | |
} | |
if (n == 0) | |
{ | |
dp[m, n] = m; | |
return dp[m, n]; | |
} | |
int mismatch = S1[m - 1] == S2[n - 1] ? 0 : 1; | |
int Insert = EditDistance(ref dp, S1, S2, m, n - 1) + 1; | |
int Remove = EditDistance(ref dp, S1, S2, m - 1, n) + 1; | |
int Replace = EditDistance(ref dp, S1, S2, m - 1, n - 1) + mismatch; | |
dp[m, n] = Min(Insert, Min(Remove, Replace)); | |
return dp[m, n]; | |
} | |
public static int LCS(ref int[,] dp, String S1, String S2, int m, int n) | |
{ | |
if (m == 0 || n == 0) | |
{ | |
dp[m, n] = 0; | |
return dp[m, n]; | |
} | |
if (S1[m - 1] == S2[n - 1]) | |
{ | |
dp[m, n] = 1 + LCS(ref dp, S1, S2, m - 1, n - 1); | |
return dp[m, n]; | |
} | |
else | |
{ | |
dp[m, n] = Max(LCS(ref dp, S1, S2, m, n - 1), LCS(ref dp, S1, S2, m - 1, n)); | |
return dp[m, n]; | |
} | |
} | |
public static int profitSellingWines(int[] p, int year, int beg, int end) | |
{ | |
if (beg > end) | |
return 0; | |
if (cache[beg, end] != -1) | |
return cache[beg, end]; | |
int tempYear = year + 1; | |
int takingLeft = profitSellingWines(p, tempYear, beg + 1, end) + year * p[beg]; | |
int takingRight = profitSellingWines(p, tempYear, beg, end - 1) + year * p[end]; | |
return cache[beg, end] = Max(takingLeft, takingRight); | |
} | |
public static int maxRod(int[] p, int n) | |
{ | |
//Recurrence:cutRod(n) = max(price[i] + cutRod(n-i-1)) for all i in {0, 1 .. n-1} | |
if (n <= 0) | |
return 0; | |
if (mem[n] != -1) | |
return mem[n]; | |
int best = int.MinValue; | |
for (int i = 0; i < n; i++) | |
{ | |
int tempBest = p[i] + maxRod(p, n - 1 - i); | |
best = Max(best, tempBest); | |
} | |
return mem[n] = best; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment