 # Dynamic programming

Set 33 (Find if a string is interleaved of two other strings) Given three strings A, B and C. Write a function that checks whether C is an interleaving of A and B. C is said to be interleaving A and B, if it contains all characters of A and B and order of all characters in individual strings is preserved. We have discussed a simple solution of this problem here. The simple solution doesn’t work if strings A and B have some common characters. For example A = “XXY”, string B = “XXZ” and string C = “XXZXXXY”. Dynamic Programming. Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces. For example, if length of the rod is 8 and the values of different pieces are given as following, then the maximum obtainable value is 22 (by cutting in two pieces of lengths 2 and 6) length | 1 2 3 4 5 6 7 8 -------------------------------------------- price | 1 5 8 9 10 17 17 20. Dynamic Programming. Set 11 (Egg Dropping Puzzle) The following is a description of the instance of this famous puzzle involving n=2 eggs and a building with k=36 floors. Suppose that we wish to know which stories in a 36-story building are safe to drop eggs from, and which will cause the eggs to break on landing. We make a few assumptions: …..An egg that survives a fall can be used again. …..A broken egg must be discarded. …..The effect of a fall is the same for all eggs. …..If an egg breaks when dropped, then it would break if dropped from a higher floor. …..If an egg survives a fall then it would survive a shorter fall. …..It is not ruled out that the first-floor windows break eggs, nor is it ruled out that the 36th-floor do not cause an egg to break.

If only one egg is available and we wish to be sure of obtaining the right result, the experiment can be carried out in only one way. Drop the egg from the first-floor window; if it survives, drop it from the second floor window. Source: Wiki for Dynamic Programming References: Set 10 ( 0-1 Knapsack Problem) Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer arrays val[0..n-1] and wt[0..n-1] which represent values and weights associated with n items respectively. Set 28 (Minimum insertions to form a palindrome) Dynamic Programming. Given n dice each with m faces, numbered from 1 to m, find the number of ways to get sum X. X is the summation of values on each face when all the dice are thrown. The Naive approach is to find all the possible combinations of values from n dice and keep on counting the results that sum to X. This problem can be efficiently solved using Dynamic Programming (DP). Why DP approach? The above problem exhibits overlapping subproblems. Please take a closer look at the above recursion. Set 33 (Find if a string is interleaved of two other strings)

Set 32 (Word Break Problem) Given an input string and a dictionary of words, find out if the input string can be segmented into a space-separated sequence of dictionary words. See following examples for more details. This is a famous Google interview question, also being asked by many other companies now a days. Consider the following dictionary { i, like, sam, sung, samsung, mobile, ice, cream, icecream, man, go, mango} Input: ilike Output: Yes The string can be segmented as "i like". Input: ilikesamsung Output: Yes The string can be segmented as "i like samsung" or "i like sam sung". Recursive implementation: The idea is simple, we consider each prefix and search it in dictionary. We strongly recommend to see substr function which is used extensively in following implementations. Dynamic Programming - Subset Sum Problem. Set 36 (Maximum Product Cutting) Given a rope of length n meters, cut the rope in different parts of integer lengths in a way that maximizes product of lengths of all parts. You must make at least one cut. Set 1 (Naive and Dynamic Programming) Travelling Salesman Problem (TSP): Given a set of cities and distance between every pair of cities, the problem is to find the shortest possible route that visits every city exactly once and returns to the starting point. Note the difference between Hamiltonian Cycle and TSP. The Hamiltoninan cycle problem is to find if there exist a tour that visits every city exactly once. Here we know that Hamiltonian Tour exists (because the graph is complete) and in fact many such tours exist, the problem is to find a minimum weight Hamiltonian Cycle. For example, consider the graph shown in figure on right side. Set 27 (Maximum sum rectangle in a 2D matrix) Given a 2D array, find the maximum sum subarray in it. For example, in the following 2D array, the maximum sum subarray is highlighted with blue rectangle and sum of this subarray is 29. This problem is mainly an extension of Largest Sum Contiguous Subarray for 1D array. The naive solution for this problem is to check every possible rectangle in given 2D array. This solution requires 4 nested loops and time complexity of this solution would be O(n^4). Set 35 (Longest Arithmetic Progression) Given a set of numbers, find the Length of the Longest Arithmetic Progression (LLAP) in it. Examples: set[] = {1, 7, 10, 15, 27, 29} output = 3 The longest arithmetic progression is {1, 15, 29} set[] = {5, 10, 15, 20, 25, 30} output = 6 The whole set is in AP For simplicity, we have assumed that the given set is sorted. We can always add a pre-processing step to first sort the set and then apply the below algorithms. Remove minimum elements from either side such that 2*min becomes more than max. Given an unsorted array, trim the array such that twice of minimum is greater than maximum in the trimmed array. Elements should be removed either end of the array. Number of removals should be minimum. Examples: Naive Solution: A naive solution is to try every possible case using recurrence. Remove minimum elements from either side such that 2*min becomes more than max. Count all possible paths from top left to bottom right of a mXn matrix. Longest Palindromic Substring. Given a string, find the longest substring which is palindrome. For example, if the given string is “forgeeksskeegfor”, the output should be “geeksskeeg”.

We have discussed dynamic programming solution in the previous post. The time complexity of the Dynamic Programming based solution is O(n^2) and it requires O(n^2) extra space. We can find the longest palindrome substring in (n^2) time with O(1) extra space. The idea is to generate all even length and odd length palindromes and keep track of the longest palindrome seen so far. Step to generate odd length palindrome: Fix a centre and expand in both directions for longer palindromes. Step to generate even length palindrome Fix two centre ( low and high ) and expand in both directions for longer palindromes. Longest Palindromic Substring.

Dynamic Programming. Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, how many ways can we make the change? The order of coins doesn’t matter. 1) Optimal Substructure To count total number solutions, we can divide all set solutions in two sets. 1) Solutions that do not contain mth coin (or Sm). 2) Solutions that contain at least one Sm. Let count(S[], m, n) be the function to count the number of solutions, then it can be written as sum of count(S[], m-1, n) and count(S[], m, n-Sm). Therefore, the problem has optimal substructure property as the problem can be solved using solutions to subproblems.