DP Problems
DP Problems
cur_len = i - prev_index;
}
return C[n][k];
}
return max;
}
int i, j;
printSolution(p, n);
}
--------------------------------------------
<--------------- River--------------->
--------------------------------------------
1 2 3 4 5 6 7 8
Source: Dynamic Programming Practice Problems. The link also has well explained solution for the
problem.
2. Maximum Sum Increasing Subsequence: Given an array of n positive integers. Write a program to
find the maximum sum subsequence of the given array such that the intgers in the subsequence are
sorted in increasing order. For example, if input is {1, 101, 2, 3, 100, 4, 5}, then output should be {1, 2, 3,
100}. The solution to this problem has been published here.
3. The Longest Chain You are given pairs of numbers. In a pair, the first number is smaller with respect
to the second number. Suppose you have two sets (a, b) and (c, d), the second set can follow the first set
if b < c. So you can form a long chain in the similar fashion. Find the longest chain which can be formed.
The solution to this problem has been published here.
4. Box Stacking You are given a set of n types of rectangular 3-D boxes, where the i^th box has height
h(i), width w(i) and depth d(i) (all real numbers). You want to create a stack of boxes which is as tall as
possible, but you can only stack a box on top of another box if the dimensions of the 2-D base of the
lower box are each strictly larger than those of the 2-D base of the higher box. Of course, you can rotate
a box so that any side functions as its base. It is also allowable to use multiple instances of the same type
of box.
// A dynamic programming solution for longest palindr.
// This code is adopted from following link
// http://www.leetcode.com/2011/11/longest-palindromic-substring-part-i.html
#include <stdio.h>
#include <string.h>
if (k > maxLength)
{
start = i;
maxLength = k;
}
}
}
}
/* A binary tree node has data, pointer to left child and a pointer to
right child */
struct node
{
int data;
int liss;
struct node *left, *right;
};
if (root->liss)
return root->liss;
return root->liss;
}
return 0;
}
// Fill table using above recursive formula. Note that the table
// is filled in diagonal fashion (similar to http://goo.gl/PQqoS),
// from diagonal elements to table[0][n-1] which is the result.
for (gap = 0; gap < n; ++gap)
{
for (i = 0, j = gap; j < n; ++i, ++j)
{
// Here x is value of F(i+2, j), y is F(i+1, j-1) and
// z is F(i, j-2) in above recursive formula
x = ((i+2) <= j) ? table[i+2][j] : 0;
y = ((i+1) <= (j-1)) ? table[i+1][j-1] : 0;
z = (i <= (j-2))? table[i][j-2]: 0;
return table[0][n-1];
}
return 0;
}
// Fill tables T1[] and T2[] using the above given recursive relations
for (i = 1; i < NUM_STATION; ++i)
{
T1[i] = min(T1[i-1] + a[0][i], T2[i-1] + t[1][i] + a[0][i]);
T2[i] = min(T2[i-1] + a[1][i], T1[i-1] + t[0][i] + a[1][i]);
}
int main()
{
int a[][NUM_STATION] = {{4, 5, 3, 2},
{2, 10, 1, 4}};
int t[][NUM_STATION] = {{0, 7, 4, 5},
{0, 9, 2, 8}};
int e[] = {10, 12}, x[] = {18, 7};
return 0;
}
// C++ program to find Length of the Longest AP (llap) in a given sorted set.
// The code strictly implements the algorithm provided in the reference.
#include <iostream>
using namespace std;
else
{
// Found i and k for j, LLAP with i and j as first two
// elements is equal to LLAP with j and k as first two
// elements plus 1. L[j][k] must have been filled
// before as we run the loop from right side
L[i][j] = L[j][k] + 1;
return 0;
}
return 0;
}
// Fill table using above recursive formula. Note that the table
// is filled in diagonal fashion i.e., from diagonal elements to
// table[0][n-1] which is the result.
for (int gap = 0; gap < n; gap++)
{
for (int i = 0, j = gap; j < n; i++, j++)
{
if (j < i+2)
table[i][j] = 0.0;
else
{
table[i][j] = MAX;
for (int k = i+1; k < j; k++)
{
double val = table[i][k] + table[k][j] + cost(points,i,j,k);
if (table[i][j] > val)
table[i][j] = val;
}
}
}
}
return table[0][n-1];
}
/* A binary tree node has data, pointer to left child and a pointer to
right child */
struct node
{
int data;
int vc;
struct node *left, *right;
};
return root->vc;
}
return 0;
}
return screen[N-1];
}
// Driver program
int main()
{
int N;
// Driver program
int main()
{
int N = 3;
cout << "Count of ways for " << N
<< " sections is " << countWays(N);
return 0;
}
return dp[m][n];
}
// Driver program
int main() {
// Base case
dp[m-1][n-1] = points[m-1][n-1] > 0? 1:
abs(points[m-1][n-1]) + 1;
// Fill last row and last column as base to fill
// entire table
for (int i = m-2; i >= 0; i--)
dp[i][n-1] = max(dp[i+1][n-1] - points[i][n-1], 1);
for (int j = n-2; j >= 0; j--)
dp[m-1][j] = max(dp[m-1][j+1] - points[m-1][j], 1);
return dp[0][0];
}
// Driver Program
int main()
{
// Initialize answer
unsigned long long int ans = 0;
// Driver program
int main()
{
int n = 3, sum = 5;
cout << finalCount(n, sum);
return 0;
}
// Initialize result
unsigned long long int ans = 0;
return ans;
}
// Driver program
int main()
{
int n = 3;
cout << "Coutn of "<<n << " digit numbers is " << finalCount(n);
return 0;
}
// C++ program to find maximum weight transformation
// of a given string
#include<bits/stdc++.h>
using namespace std;
// Driver program
int main()
{
string str = "AAAAABB";
cout << "Maximum weight of a transformation of "
<< str << " is " << getMaxWeight(str);
return 0;
}
// Driver Program
int main()
{
string str = "aabb";
cout << "The length of the largest subsequence that"
" repeats itself is : "
<< findLongestRepeatingSubSeq(str);
return 0;
}
return count[dist];
}
// driver program
int main()
{
int dist = 4;
cout << printCountDP(dist);
return 0;
}
return result;
}
// Driver program
int main()
{
int mat[n][n] = {{1, 2, 9},
{5, 3, 8},
{4, 6, 7}};
cout << "Length of the longest path is "
<< finLongestOverAll(mat);
return 0;
}
return dp[rhs];
}
// Driver program
int main()
{
int coeff[] = {2, 2, 5};
int rhs = 4;
int n = sizeof(coeff)/sizeof(coeff[0]);
cout << countSol(coeff, n, rhs);
return 0;
}
int dp[R][C][MAX_K];
return dp[m][n][k];
}
// Get the maximum of two cases when you are facing right
// in this cell
if (dir == 1) // Direction is right
dp[i][j][dir] += max(maxCoinsUtil(arr, i+1, j, 0, dp), // Down
maxCoinsUtil(arr, i, j+1, 1, dp)); // Ahead in
rught
// Get the maximum of two cases when you are facing left
// in this cell
if (dir == 0) // Direction is left
dp[i][j][dir] += max(maxCoinsUtil(arr, i+1, j, 1, dp), // Down
maxCoinsUtil(arr, i, j-1, 0, dp)); // Ahead in
left
return 0;
}
int bellNumber(int n)
{
int bell[n+1][n+1];
bell[0][0] = 1;
for (int i=1; i<=n; i++)
{
// Explicitly fill for j = 0
bell[i][0] = bell[i-1][i-1];
// Driver program
int main()
{
for (int n=0; n<=5; n++)
cout << "Bell Number " << n << " is "
<< bellNumber(n) << endl;
return 0;
}
// A C++ program to count number of partitions
// of a set with n elements into k subsets
#include<iostream>
using namespace std;
// Driver program
int main()
{
cout << countP(3, 2);
return 0;
}
int countDer(int n)
{
// Create an array to store counts for subproblems
int der[n + 1];
// Base cases
der[0] = 1;
der[1] = 0;
der[2] = 1;
// Driver program
int main()
{
int n = 4;
cout << "Count of Derangements is " << countDer(n);
return 0;
// A Recursive C program to solve minimum sum partition
// problem.
#include <bits/stdc++.h>
using namespace std;
/* Driver program */
int main()
{
int arr[] = { 10, 22, 9, 33, 49, 50, 31, 60 };
int n = sizeof(arr)/sizeof(arr[0]);
printf("Length of Longest Zig-Zag subsequence is %d\n",
zzis(arr, n) );
return 0;
}
return dp[p][q][r][last];
}
// Driver code
int main()
{
int arr1[] = {10, 5, 2, 7, 10};
int n1 = sizeof(arr1)/sizeof(arr1[0]);
cout << minTime(arr1, n1) << endl;
return 0;
}
return result;
}
// If n = 0, no solution exists
task_dp[0] = 0;
#define M 100
return res;
}
return 0;
}
// C++ program to find length of the longest geometric
// progression in a given set
#include <iostream>
#include <algorithm>
using namespace std;
// Return result
return llgp;
}
// Driver code
int main()
{
int set1[] = {1, 3, 9, 27, 81, 243};
int n1 = sizeof(set1)/sizeof(set1[0]);
cout << lenOfLongestGP(set1, n1) << "\n";
return 0;
}
/* C++ code to find minimum cost to make two strings
identical */
#include<bits/stdc++.h>
using namespace std;
else
L[i][j] = max(L[i-1][j], L[i][j-1]);
}
}
else
// If last character are different, ignore
// last character of first string
lookup[i][j] = lookup[i - 1][j];
}
}
return lookup[m][n];
}
// Driver code
int main()
{
string a = "GeeksforGeeks";
string b = "Gks";
return 0;
}
return dp[n];
}
// Driver code
int main()
{
cout << countSub("gfg");
return 0;
}
// A Dynamic Programming based C++ program to
// find minimum possible sum of elements of array
// such that an element out of every three
// consecutive is picked.
#include <iostream>
using namespace std;
// Driver code
int main()
{
int arr[] = {1, 2, 3, 20, 2, 10, 1};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Min Sum is " << findMinSum(arr, n);
return 0;
}
// C++ program to find the longest repeated
// non-overlapping substring
#include<bits/stdc++.h>
using namespace std;
// Setting all to 0
memset(LCSRe, 0, sizeof(LCSRe));
return res;
}
// Limit on N and K
const int M = 100
return sum;
}
/**
* http://www.geeksforgeeks.org/dynamic-programming-set-15-longest-bitonic-
subsequence/
*/
public class BitonicSequence {
}
}
package com.interview.dynamic;
/**
* Date 03/02/2016
* @author Tushar Roy
*
* Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on
it represented
* by array nums. You are asked to burst all the balloons. If the you burst balloon i
you will
* get nums[left] * nums[i] * nums[right] coins. Here left and right are adjacent
indices of i. After the burst,
* the left and right then becomes adjacent.
* Find the maximum coins you can collect by bursting the balloons wisely.
*
* Time complexity O(n^3)
* Space complexity O(n^2)
*
* Reference
* https://leetcode.com/problems/burst-balloons/
*/
public class BurstBalloons {
/**
* Dynamic programming solution.
*/
public int maxCoinsBottomUpDp(int[] nums) {
int max = 0;
for (int i = 1; i < nums.length - 1; i++) {
int val = nums[i - 1]*nums[i]*nums[i+1] +
maxCoinsRecUtil(formNewArray(nums, i));
if (val > max) {
max = val;
}
}
return max;
/**
* Space efficient DP solution
*/
public int numberOfSolutionsOnSpace(int total, int arr[]){
temp[0] = 1;
for(int i=0; i < arr.length; i++){
for(int j=1; j <= total ; j++){
if(j >= arr[i]){
temp[j] += temp[j-arr[i]];
}
}
}
return temp[total];
}
/**
* This method actually prints all the combination. It takes exponential time.
*/
public void printCoinChangingSolution(int total,int coins[]){
List<Integer> result = new ArrayList<>();
printActualSolution(result, total, coins, 0);
}
private void printActualSolution(List<Integer> result,int total,int coins[],int pos){
if(total == 0){
for(int r : result){
System.out.print(r + " ");
}
System.out.print("\n");
}
for(int i=pos; i < coins.length; i++){
if(total >= coins[i]){
result.add(coins[i]);
printActualSolution(result,total-coins[i],coins,i);
result.remove(result.size()-1);
}
}
}
import java.text.Format;
import java.util.HashMap;
import java.util.Map;
/**
* Date 08/12/2013
* @author Tushar Roy
*
* Given a total and coins of certain denomination with infinite supply, what is the minimum number
* of coins it takes to form this total.
*
* Time complexity - O(coins.size * total)
* Space complexity - O(coins.size * total)
*
* Youtube video -
* Topdown DP - https://youtu.be/Kf_M7RdHr1M
* Bottom up DP - https://youtu.be/Y0ZqKpToTic
*/
public class CoinChangingMinimumCoin {
/**
* Top down dynamic programing. Using map to store intermediate results.
* Returns Integer.MAX_VALUE if total cannot be formed with given coins
*/
public int minimumCoinTopDown(int total, int coins[], Map<Integer, Integer> map) {
//if map contains the result means we calculated it before. Lets return that value.
if ( map.containsKey(total) ) {
return map.get(total);
}
//iterate through all coins and see which one gives best result.
int min = Integer.MAX_VALUE;
for ( int i=0; i < coins.length; i++ ) {
//if value of coin is greater than total we are looking for just continue.
if( coins[i] > total ) {
continue;
}
//recurse with total - coins[i] as new total
int val = minimumCoinTopDown(total - coins[i], coins, map);
//if val we get from picking coins[i] as first coin for current total is less
// than value found so far make it minimum.
if( val < min ) {
min = val;
}
}
//if min is MAX_VAL dont change it. Just result it as is. Otherwise add 1 to it.
min = (min == Integer.MAX_VALUE ? min : min + 1);
/**
* Bottom up way of solving this problem.
* Keep input sorted. Otherwise temp[j-arr[i]) + 1 can become Integer.Max_value + 1 which
* can be very low negative number
* Returns Integer.MAX_VALUE - 1 if solution is not possible.
*/
public int minimumCoinBottomUp(int total, int coins[]){
int T[] = new int[total + 1];
int R[] = new int[total + 1];
T[0] = 0;
for(int i=1; i <= total; i++){
T[i] = Integer.MAX_VALUE-1;
R[i] = -1;
}
for(int j=0; j < coins.length; j++){
for(int i=1; i <= total; i++){
if(i >= coins[j]){
if (T[i - coins[j]] + 1 < T[i]) {
T[i] = 1 + T[i - coins[j]];
R[i] = j;
}
}
}
}
printCoinCombination(R, coins);
return T[total];
}
}
}
package com.interview.dynamic;
/**
* http://www.geeksforgeeks.org/count-number-binary-strings-without-consecutive-1s/
* It is really a straight up fibonacci series with values
* 1,2,3,5,8,13....
* Look how we assign a[i] value of a[i-1] + b[i-1] and then b[i] becomes a[i]
*/
public class CountNumberOfBinaryWithoutConsecutive1s {
a[0] = 1;
b[0] = 1;
return a + b;
}
/**
* http://www.geeksforgeeks.org/program-nth-catalan-number/
* Count number of binary search tree created for array of size n
*/
public class CountNumberOfTreesInBST {
package com.interview.dynamic;
* Given a rod with markings. Cut the rod along markings but reduce the cost of
cutting.
* Cost if cutting is proportional to the length of rod being cut.
*
* Solve is using top down dynamic programming. Memoize minimum cost of cutting
between marking
* start to end. To calculate the value try all markings b/w start to end.
*
*/
public class CutRodToMinimizeCost {
if(T[start][end] != -1) {
return T[start][end];
}
int i;
for(i=0; i < markings.length; i++){
if(start < markings[i]) {
break;
}
}
if(i == markings.length) {
T[start][end] = 0;
return 0;
}
int j;
for(j=markings.length -1; j >= 0; j--){
if(end > markings[j]) {
break;
}
}
if(j == -1) {
T[start][end] = 0;
return 0;
}
if(i == j){
T[start][end] = end - start;
return end - start;
}
int cost = end - start;
int minCost = Integer.MAX_VALUE;
for(int k=i; k <= j; k++) {
int c1 = cutRodToMinimizeCost(markings, start, markings[k], T);
int c2 = cutRodToMinimizeCost(markings, markings[k], end, T);
if(c1 == Integer.MAX_VALUE || c2 == Integer.MAX_VALUE) {
continue;
}
if(minCost > c1 + c2){
minCost = c1 + c2;
}
}
if(minCost == Integer.MAX_VALUE) {
T[start][end] = Integer.MAX_VALUE;
return Integer.MAX_VALUE;
}
T[start][end] = cost + minCost;
return cost + minCost;
}
package com.interview.dynamic;
/**
* http://www.geeksforgeeks.org/dynamic-programming-set-13-cutting-a-rod/
*/
public class CuttingRod {
int c2 = 0;
if (start < s.length() - 1) {
s1 = s.substring(start, start + 2);
if (Integer.valueOf(s1) <= 26) {
c2 = numDecodingsUtil(s, start + 2, count);
}
}
count.put(start, c1 + c2);
return c1 + c2;
}
}
package com.interview.dynamic;
/**
* @author Tushar Roy
* http://www.geeksforgeeks.org/dice-throw-problem/
* This solution assumes that 1,2,1 is different from 2,1,1 which is different from
1,1 2
* so total 3 ways are possible
*/
public class DiceThrowWays {
import java.util.List;
* Given two strings how many minimum edits(update, delete or add) is needed to
convert one string to another
*
* Time complexity is O(m*n)
* Space complexity is O(m*n)
*
public class EditDistance {
/**
* Uses recursion to find minimum edits
*/
public int recEditDistance(char[] str1, char str2[], int len1,int len2){
if(len1 == str1.length){
return str2.length - len2;
}
if(len2 == str2.length){
return str1.length - len1;
}
return min(recEditDistance(str1, str2, len1 + 1, len2 + 1) + str1[len1] ==
str2[len2] ? 0 : 1, recEditDistance(str1, str2, len1, len2 + 1) + 1,
recEditDistance(str1, str2, len1 + 1, len2) + 1);
}
/**
* Uses bottom up DP to find the edit distance
*/
public int dynamicEditDistance(char[] str1, char[] str2){
int temp[][] = new int[str1.length+1][str2.length+1];
/**
* Prints the actual edits which needs to be done.
*/
public void printActualEdits(int T[][], char[] str1, char[] str2) {
int i = T.length - 1;
int j = T[0].length - 1;
while(true) {
if (i == 0 || j == 0) {
break;
}
if (str1[i-1] == str2[j-1]) {
i = i-1;
j = j-1;
} else if (T[i][j] == T[i-1][j-1] + 1){
System.out.println("Edit " + str2[j-1] + " in string2 to " + str1[i-
1] + " in string1");
i = i-1;
j = j-1;
} else if (T[i][j] == T[i-1][j] + 1) {
System.out.println("Delete in string1 " + str1[i-1]);
i = i-1;
} else if (T[i][j] == T[i][j-1] + 1){
System.out.println("Delete in string2 " + str2[j-1]);
j = j -1;
} else {
throw new IllegalArgumentException("Some wrong with given data");
}
}
}
}
package com.interview.dynamic;
/**
* http://www.geeksforgeeks.org/dynamic-programming-set-11-egg-dropping-puzzle/
*/
public class EggDropping {
/**
* Date 03/11/2016
* @author Tushar Roy
*
* Given a 2D array find the sum in given range defining a rectangle.
*
* Time complexity construction O(n*m)
* Time complexity of query O(1)
* Space complexity is O(n*m)
*
* Reference
* https://leetcode.com/problems/range-sum-query-2d-immutable/
*/
public class Immutable2DSumRangeQuery {
private int[][] T;
public int sumQuery(int row1, int col1, int row2, int col2) {
row1++;
col1++;
row2++;
col2++;
return T[row2][col2] - T[row1 - 1][col2] - T[row2][col1 - 1] + T[row1 -
1][col1 - 1];
}
int[][] input1 = {{2,0,-3,4}, {6, 3, 2, -1}, {5, 4, 7, 3}, {2, -6, 8, 1}};
Immutable2DSumRangeQuery isr = new Immutable2DSumRangeQuery(input1);
System.out.println(isr.sumQuery(1, 1, 2, 2));
}
}
package com.interview.dynamic;
/**
http://www.geeksforgeeks.org/dynamic-programming-set-4-longest-common-subsequence/
*/
public class LongestCommonSubsequence {
}
package com.interview.dynamic;
/**
* http://en.wikipedia.org/wiki/Longest_common_substring_problem
*/
public class LongestCommonSubstring {
/**
* Dynamic way of calculating lcs
*/
public int longestCommonSubstring(char str1[], char str2[]){
int T[][] = new int[str1.length+1][str2.length+1];
int max = 0;
for(int i=1; i <= str1.length; i++){
for(int j=1; j <= str2.length; j++){
if(str1[i-1] == str2[j-1]){
T[i][j] = T[i-1][j-1] +1;
if(max < T[i][j]){
max = T[i][j];
}
}
}
}
return max;
}
/**
* Recursive way of calculating lcs
*/
public int longestCommonSubstringRec(char str1[], char str2[], int pos1, int
pos2, boolean checkEqual){
if(pos1 == -1 || pos2 == -1){
return 0;
}
if(checkEqual){
if(str1[pos1] == str2[pos2]){
return 1 + longestCommonSubstringRec(str1, str2, pos1-1, pos2-1,
true);
}else{
return 0;
}
}
int r1 = 0;
if(str1[pos1] == str2[pos2]){
r1 = 1 + longestCommonSubstringRec(str1, str2, pos1-1, pos2-1, true);
}
return Math.max(r1,Math.max(longestCommonSubstringRec(str1, str2, pos1-1,
pos2, false), longestCommonSubstringRec(str1, str2, pos1, pos2-1,false)));
}
}
package com.interview.dynamic;
/**
* http://www.geeksforgeeks.org/longest-even-length-substring-sum-first-second-half/
* Test cases
* Even length string
* odd length string
* 0 length string
*/
public class LongestEvenLengthSubstringOfEqualHalf {
if(len % 2 == 0){
int k = (i + j)/2;
if(T[i][k] == T[k+1][j]){
if(max < len){
max = len;
}
}
}
}
}
return max;
}
/**
* Date 03/10/2016
* @author Tushar Roy
*
* Given a 2D matrix find longest increasing path length in this matrix.
*
* Time complexity is O(n*m)
* Space complexity is O(n*m)
*
* Reference
* https://leetcode.com/problems/longest-increasing-path-in-a-matrix/
*/
public class LongestIncreasingPath {
if (distance[i][j] != 0) {
return distance[i][j];
}
/**
* DP way of solving LIS
*/
public int longestSubsequenceWithActualSolution(int arr[]){
int T[] = new int[arr.length];
int actualSolution[] = new int[arr.length];
for(int i=0; i < arr.length; i++){
T[i] = 1;
actualSolution[i] = i;
}
return T[maxIndex];
}
/**
* Recursive way of solving LIS
*/
public int longestSubsequenceRecursive(int arr[]){
int maxLen = 0;
for(int i=0; i < arr.length-1; i++){
int len = longestSubsequenceRecursive(arr,i+1,arr[i]);
if(len > maxLen){
maxLen = len;
}
}
return maxLen + 1;
}
/**
* Date 02/11/2016
* @author Tushar Roy
*
* Wild car matching with ? and *
*
* Reference
* https://leetcode.com/problems/wildcard-matching/
*/
public class WildCardMatching {
public boolean isMatch(String s, String p) {
char[] str = s.toCharArray();
char[] pattern = p.toCharArray();
T[0][0] = true;
return T[str.length][writeIndex];
}
/**
* Recursive and slow version of wild card matching.
*/
public boolean isMatchRecursive(String s, String p) {
return isMatchRecursiveUtil(s.toCharArray(), p.toCharArray(),
0, 0);
}
if (pattern[pos2] != '*') {
if (pos1 < text.length && (text[pos1] == pattern[pos2]) ||
pattern[pos2] == '?') {
return isMatchRecursiveUtil(text, pattern, pos1 + 1,
pos2 + 1);
} else {
return false;
}
} else {
//if we have a***b then skip to the last *
while (pos2 < pattern.length - 1 && pattern[pos2 + 1] ==
'*') {
pos2++;
}
pos1--;
while (pos1 < text.length) {
if (isMatchRecursiveUtil(text, pattern, pos1 + 1, pos2
+ 1)) {
return true;
}
pos1++;
}
return false;
}
}
package com.interview.dynamic;
import java.util.Arrays;
import java.util.Comparator;
class Job{
int start;
int end;
int profit;
Job(int start,int end,int profit){
this.start= start;
this.end = end;
this.profit= profit;
}
}
@Override
public int compare(Job arg0, Job arg1) {
if(arg0.end <= arg1.end){
return -1;
}else{
return 1;
}
}
/**
*
http://www.cs.princeton.edu/courses/archive/spr05/cos423/lectures/06dy
namic-programming.pdf
* Given set of jobs with start and end interval and profit, how to
maximize profit such that
* jobs in subset do not overlap.
*/
/**
* Sort the jobs by finish time.
* For every job find the first job which does not overlap with
this job
* and see if this job profit plus profit till last non
overlapping job is greater
* than profit till last job.
* @param jobs
* @return
*/
public int maximum(Job[] jobs){
int T[] = new int[jobs.length];
FinishTimeComparator comparator = new FinishTimeComparator();
Arrays.sort(jobs, comparator);
T[0] = jobs[0].profit;
for(int i=1; i < jobs.length; i++){
T[i] = Math.max(jobs[i].profit, T[i-1]);
for(int j=i-1; j >=0; j--){
if(jobs[j].end <= jobs[i].start){
T[i] = Math.max(T[i], jobs[i].profit + T[j]);
break;
}
}
}
int maxVal = Integer.MIN_VALUE;
for (int val : T) {
if (maxVal < val) {
maxVal = val;
}
}
return maxVal;
}
package com.interview.dynamic;
import java.util.PriorityQueue;
/**
* Date 03/08/2016
* @author Tushar Roy
*
* Find nth ugly number.
*
* https://leetcode.com/problems/ugly-number-ii/
* https://leetcode.com/problems/super-ugly-number/
* http://www.geeksforgeeks.org/ugly-numbers/
*/
@Override
public int compareTo(Node other) {
return this.val - other.val;
}
}
return arr[n-1];
}
package com.interview.dynamic;
/**
*
* http://www.geeksforgeeks.org/check-whether-a-given-string-is-an-
interleaving-of-two-other-given-strings-set-2/
*/
public class TwoStringInterleavingToFormThird {
if(pos3 == str3.length){
return false;
}
}
public boolean isInterleaved(char str1[], char str2[], char
str3[]){
boolean T[][] = new boolean[str1.length +1][str2.length +1];
package com.interview.dynamic;
/**
* Date 05/07/2015
* @author tusroy
*
* Video link - https://youtu.be/RORuwHiblPc
*
* Given a sequence of words, and a limit on the number of characters
that can be put
* in one line (line width). Put line breaks in the given sequence
such that the
* lines are printed neatly
*
* Solution:
* Badness - We define badness has square of empty spaces in every
line. So 2 empty space
* on one line gets penalized as 4 (2^2) while 1 each empty space on 2
lines gets
* penalized as 2(1 + 1). So we prefer 1 empty space on different
lines over 2 empty space on
* one line.
*
* For every range i,j(words from i to j) find the cost of putting
them on one line. If words
* from i to j cannot fit in one line cost will be infinite. Cost is
calculated as square of
* empty space left in line after fitting words from i to j.
*
* Then apply this formula to get places where words need to be going
on new line.
* minCost[i] = minCost[j] + cost[i][j-1]
* Above formula will try every value of j from i to len and see which
one gives minimum
* cost to split words from i to len.
*
* Space complexity is O(n^2)
* Time complexity is O(n^2)
*
* References:
* http://www.geeksforgeeks.org/dynamic-programming-set-18-word-wrap/
*/
public class TextJustification {
return builder.toString();
}
package com.interview.dynamic;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Date 01/06/2016
* @author Tushar Roy
* Let there be a binary operation for 3 symbols a, b, c and result of
these binary operation given in a table.
* Given an expression of these 3 symbols and a final result, tell if
this expression can be parenthesize in certain
* way to produce the final result.
*
* Time complexity is O(n^4)
* Space complexity is O(n^3)
*/
public class SymbolExpressionEvaluation {
T[i][j].add(input[index.get(ch)][index.get(ch1)]);
}
}
}
}
}
char input[][] = {{'b', 'b', 'a'}, {'c', 'b', 'a'}, {'a', 'c',
'c'}};
SymbolExpressionEvaluation sbe = new
SymbolExpressionEvaluation();
System.out.println(sbe.evaluateExpression(input, index,
"bbbbac".toCharArray(), 'a'));
}
class Holder {
private Set<Character> valueHolder = new HashSet<>();
void add(Character ch) {
valueHolder.add(ch);
}
Set<Character> values() {
return valueHolder;
}
}
package com.interview.dynamic;
/**
* Date 09/15/2014
* @author tusroy
*
* Find maximum subsquare in a matrix made up of Xs and Os such that
all four sides of subsquare are Xs. It does not matter what is inside
* the subsquare. All 4 sides should be made up entirely of Xs
*
* e.g
* 0 0 0 0 0 X 0,0 0,0 0,0 0,0 0,0 1,1
* 0 X 0 X X X 0,0 1,1 0,0 1,1 1,2 2,3
* 0 X 0 X 0 X 0,0 2,1 0,0 2,1 0,0 3,1
* 0 X X X X X 0,0 3,1 1,2 3,3 1,4 4,5
* 0 0 0 0 0 0 0,0 0,0 0,0 0,0 0,0 0,0
*
* Output of above program should be 3
*
* Solution
* Have another matrix which is capable of holding 2 values hori and
ver.
* Ver stores how far vertically you can see Xs. Hori stores how far
horizontally you can see Xs.
* Once this matrix is build look for biggest subsquare by getting min
of hori and ver at each point and checking
* if subsquare can be formed from value min to 1.
*
* Test cases:
* Matrix entirely made up of Xs
* Matrix entirely made up of Os
* Matrix with Xs and Os but maximum subsquare is length 1
*/
public class SubsquareSurrounedByXs {
class Cell{
int ver;
int hori;
}
public int findSubSquare(char input[][]){
Cell T[][] = new Cell[input.length][input[0].length];
for(int i=0; i < T.length; i++){
for(int j=0; j < T[0].length; j++){
T[i][j] = new Cell();
}
}
return max;
}
package com.interview.dynamic;
/*
* Date 09/23/2014
* @author Tushar Roy
*
* Given an array of non negative numbers and a total, is there subset
of numbers in this array which adds up
* to given total. Another variation is given an array is it possible
to split it up into 2 equal
* sum partitions. Partition need not be equal sized. Just equal sum.
*
* Time complexity - O(input.size * total_sum)
* Space complexity - O(input.size*total_sum)
*
* Youtube video - https://youtu.be/s6FhG--P7z0
*/
public class SubsetSum {
if (sum % 2 != 0) {
return false;
}
sum = sum / 2;
boolean[][] T = new boolean[arr.length + 1][sum + 1];
}
}
package com.interview.dynamic;
/**
* Date 07/31/2014
* @author tusroy
*
* Write a program to find maximum sum rectangle in give 2D matrix.
* Assume there is at least one positive number in the 2D matrix.
*
* Solution:
* Keep temp array with size as number of rows. Start left and right
from 0
* and keep adding values for each row and maintain them in this temp
array.
* Run Kadane's algorithm to find max sum subarray in temp. Now
increment right by
* 1. When right reaches last column reset right to 1 and left to 1.
*
* Space complexity of this algorithm is O(row)
* Time complexity of this algorithm is O(row*col*col)
*
* References
* http://www.geeksforgeeks.org/dynamic-programming-set-27-max-sum-
rectangle-in-a-2d-matrix/
*/
public class SubRectangularMatrixWithMaximumSum {
class Result{
int maxSum;
int leftBound;
int rightBound;
int upBound;
int lowBound;
@Override
public String toString() {
return "Result [maxSum=" + maxSum + ", leftBound=" +
leftBound
+ ", rightBound=" + rightBound + ", upBound=" +
upBound
+ ", lowBound=" + lowBound + "]";
}
class KadaneResult{
int maxSum;
int start;
int end;
public KadaneResult(int maxSum, int start, int end) {
this.maxSum = maxSum;
this.start = start;
this.end = end;
}
}
package com.interview.dynamic;
import java.util.Deque;
import java.util.LinkedList;
/**
* Date 12/22/2015
* @author Tushar Roy
*
* Given stockc prices for certain days and at most k transactions how
to buy and sell
* to maximize profit.
*
* Time complexity - O(number of transactions * number of days)
* Space complexity - O(number of transcations * number of days)
*
* https://leetcode.com/discuss/15153/a-clean-dp-solution-which-
generalizes-to-k-transactions
*/
public class StockBuySellKTransactions {
/**
* This is faster method which does optimization on slower method
* Time complexity here is O(K * number of days)
*
* Formula is
* T[i][j] = max(T[i][j-1], prices[j] + maxDiff)
* maxDiff = max(maxDiff, T[i-1][j] - prices[j])
*/
public int maxProfit(int prices[], int K) {
if (K == 0 || prices.length == 0) {
return 0;
}
int T[][] = new int[K+1][prices.length];
/**
* This is slow method but easier to understand.
* Time complexity is O(k * number of days ^ 2)
* T[i][j] = max(T[i][j-1], max(prices[j] - prices[m] + T[i-
1][m])) where m is 0...j-1
*/
public int maxProfitSlowSolution(int prices[], int K) {
if (K == 0 || prices.length == 0) {
return 0;
}
int T[][] = new int[K+1][prices.length];
while(!stack.isEmpty()) {
System.out.println("Buy at price " +
prices[stack.pollFirst()]);
System.out.println("Sell at price " +
prices[stack.pollFirst()]);
}
package com.interview.dynamic;
import java.util.HashMap;
import java.util.Map;
/**
* Read question at https://leetcode.com/problems/scramble-string/
*/
public class ScrambledString {
/**
* Index for memoization.
*/
private static class Index {
int start1;
int end1;
int start2;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
@Override
public int hashCode() {
int result = start1;
result = 31 * result + end1;
result = 31 * result + start2;
result = 31 * result + end2;
return result;
}
int end2;
}
//if we have already calculated value for index then lets use
it instead of recalculating again.
if(memMap.containsKey(index)) {
return memMap.get(index);
}
//if both input from their respective start to end are same
then return true.
boolean isSame = true;
for(int i= start1, j = start2; i <= end1 && j <= end2; i++,
j++) {
if(input1[i] != input2[j]) {
isSame = false;
break;
}
}
if(isSame) {
memMap.put(index, true);
return true;
}
//for values from input range try splitting into 2 and check
recursively if they match or not.
for(int len = 0; len < end1 - start1; len++) {
//e.g great gtear so match g ,g and reat, tear
if(isScrambled(input1, input2, start1, start1 + len,
start2, start2 + len, memMap) &&
isScrambled(input1, input2, start1 + len +1, end1,
start2 + len + 1, end2, memMap)) {
memMap.put(index, true);
return true;
}
//e.g great reatg so match g,g and reat,reat
if(isScrambled(input1, input2, start1, start1 + len, end2
- len, end2, memMap) &&
isScrambled(input1, input2, start1 + len +1, end1,
start2, end2 - len -1, memMap)) {
memMap.put(index, true);
return true;
}
}
memMap.put(index, false);
return false;
}
package com.interview.dynamic;
/**
* http://www.geeksforgeeks.org/remove-minimum-elements-either-side-
2min-max/
*/
public class RemoveFromEndToMake2IntoMinGreaterThanMax {
return Math.min(removeFromEnd(input,low,high-1),
removeFromEnd(input,low+1,high)) +1;
}
package com.interview.dynamic;
/**
* Date 06/24/2015
* @author Tushar Roy
*
* Write a program to perform regex matching with * an .
*
* References : http://leetcode.com/2011/09/regular-expression-
matching.html
*/
public class RegexMatching {
//if we have case like abc and ad*bc so here we totally skip
d*
if(matchRegexRecursive(text, pattern, pos1, pos2+2)){
return true;
}
//For case like abbc and ab*c match first b with b* and then
next b to c. If that does not work out
//then try next b with b* and then c with c and so on.
//if pattern current val is . then skip one character at time
from text till we either reach end of text
//or a match is found
while(pos1 < text.length && (text[pos1] == pattern[pos2] ||
pattern[pos2] == '.')){
if( matchRegexRecursive(text, pattern, pos1+1, pos2+2)){
return true;
}
pos1++;
}
return false;
}
/**
* Dynamic programming technique for regex matching.
*/
public boolean matchRegex(char[] text, char[] pattern) {
boolean T[][] = new boolean[text.length + 1][pattern.length +
1];
T[0][0] = true;
//Deals with patterns like a* or a*b* or a*b*c*
for (int i = 1; i < T[0].length; i++) {
if (pattern[i-1] == '*') {
T[0][i] = T[0][i - 2];
}
}
System.out.println(rm.matchRegexRecursive("Tushar".toCharArray(),"Tush
ar".toCharArray()));
System.out.println(rm.matchRegexRecursive("Tusha".toCharArray(),"Tusha
r*a*b*".toCharArray()));
System.out.println(rm.matchRegexRecursive("".toCharArray(),"a*b*".toCh
arArray()));
System.out.println(rm.matchRegexRecursive("abbbbccc".toCharArray(),"a*
ab*bbbbc*".toCharArray()));
System.out.println(rm.matchRegexRecursive("abbbbccc".toCharArray(),"aa
*bbb*bbbc*".toCharArray()));
System.out.println(rm.matchRegexRecursive("abbbbccc".toCharArray(),".*
bcc".toCharArray()));
System.out.println(rm.matchRegexRecursive("abbbbccc".toCharArray(),".*
bcc*".toCharArray()));
System.out.println(rm.matchRegexRecursive("abbbbccc".toCharArray(),".*
bcc*".toCharArray()));
System.out.println(rm.matchRegexRecursive("aaa".toCharArray(),"ab*a*c*
a".toCharArray()));
System.out.println(rm.matchRegex("aa".toCharArray(),
"a*".toCharArray()));
}
}
package com.interview.dynamic;
import java.util.HashMap;
import java.util.Map;
/**
* Given the mobile numeric keypad. You can only press buttons that
are
* up,left,right or down to the current button.You are not allowed to
press
* bottom row corner buttons (i.e. * and # ).Given a N find out the
number of
* numbers possible of given length.
*
* The idea is that to calculate for i all you have to do is add up i-
1 values of all the neighbors.
* e.g for i =2 and at 0 you need find i=1s of all neighbors including
0 and add them up.
*/
public class PhoneDialNumberOfCombinationOfSizeK {
/**
* -1 in the input means don't use that position
*
* @param k
* @param input
* @return
*/
public int numberOfCombination(int k, int input[][]) {
if (input == null || input.length == 0) {
throw new IllegalArgumentException();
}
Map<Integer, Integer> t = new HashMap<Integer, Integer>();
Map<Integer, Integer> t1 = new HashMap<Integer, Integer>();
package com.interview.dynamic;
import java.util.*;
/**
* Date 04/03/2016
* @author Tushar Roy
*
* Partitioning the string into palindromes.
*
* https://leetcode.com/problems/palindrome-partitioning/
* https://leetcode.com/problems/palindrome-partitioning-ii/
*/
public class PalindromePartition {
/*
* Given a string s, partition s such that every substring of the
partition is a palindrome.
* Return the minimum cuts needed for a palindrome partitioning of
s.
* https://leetcode.com/problems/palindrome-partitioning-ii/
*/
public int minCut(String str){
if (str.length() == 0) {
return 0;
}
/**
* Given a string s, partition s such that every substring of the
partition is a palindrome.
* https://leetcode.com/problems/palindrome-partitioning/
*/
public List<List<String>> partition(String s) {
Map<Integer, List<List<String>>> dp = new HashMap<>();
List<List<String>> result = partitionUtil(s, dp, 0);
List<List<String>> r = new ArrayList<>();
for (List<String> l : result) {
r.add(l);
}
return r;
}
if (dp.containsKey(start)) {
return dp.get(start);
}
package com.interview.dynamic;
/**
* Paint House 2
* https://leetcode.com/problems/paint-house-ii/
*/
public class PaintHouse {
public int minCost(int[][] costs) {
if (costs.length == 0 || costs[0].length == 0) {
return 0;
}
int[][] dp = new int[costs.length][costs[0].length];
for (int i = 0; i < costs[0].length; i++) {
dp[0][i] = costs[0][i];
}
class Pair {
int minIndex;
int secondMinIndex;
}
package com.interview.dynamic;
/**
* http://www.geeksforgeeks.org/dynamic-programming-set-24-optimal-
binary-search-tree/
*/
public class OptimalTreeSearch {
return minCostRec(input,freq,0,input.length-1,1);
}
package com.interview.dynamic;
/**
* Finding the number of ways a given score could be reached for a
game with 3 different ways of scoring (e.g. 3, 5 and 10 points).
*test case
*what happens if total can't be formed with given values
*what if numbers are 0 or negative
*/
public class NumberOfWaysToScorePoints {
//in this version to make 3 - 1,2 and 2,1 are counted different.
//This is same as fibo series only that fibo series looks at last
2 numbers and here we look back k values
public int version2(int score[],int total){
int T[] = new int[total+1];
T[0] = 1;
for(int i=1; i <= total ; i++){
for(int j=0; j < score.length; j++){
if(score[j] <= i){
T[i] += T[i-score[j]];
}
}
}
return T[total];
}
package com.interview.dynamic;
/**
* http://www.geeksforgeeks.org/count-possible-paths-top-left-bottom-
right-nxm-matrix/
*/
public class NumberOfPathsInMxNMatrix {
package com.interview.dynamic;
/**
* http://www.glassdoor.com/Interview/N-pots-each-with-some-number-of-
gold-coins-are-arranged-in-a-line-You-are-playing-a-game-against-
another-player-You-tak-QTN_350584.htm
* @author tusroy
* @author Z. Berkay Celik
*/
public class NPotGold {
return moves;
}
//prints the sequence of values and indexes
public void printSequence(int pots[], Pair moves[][]){
int i = 0;
int j = pots.length - 1;
int step;
for (int k = 0; k < pots.length; k++) {
step = moves[i][j].pick;
//this is the value of pick and its index
System.out.print("value: " + pots[step] + " " + "index: "
+ step + " ");
if (step <= i) {
i = i + 1;
} else {
j = j - 1;
}
}
}
public static void main(String args[]){
NPotGold npg = new NPotGold();
int pots[] = {3,1,5,6,2,9,3};
Pair[][] moves = npg.findMoves(pots);
for(int i=0; i < moves.length; i++){
for(int j=0; j < moves[i].length; j++){
System.out.print(moves[i][j] + " ");
}
System.out.print("\n");
}
System.out.println("The moves by first player and second
player:");
npg.printSequence(pots, moves);
}
}
package com.interview.dynamic;
import java.util.Arrays;
/**
* Date 06/12/2014
* @author tusroy
*
* Given an array of non negative integers where each element
represents the max
* number of steps that can be made forward from that element. Write a
function to
* return the minimum number of jumps to reach the end of the array
from first element
*
* Solution
* Have 2 for loop. j trails i. If arr[j] + j >= i then you calculate
new jump
* and result.
*
* Space complexity O(n) to maintain result and min jumps
* Time complexity O(n^2)
*
* Reference
* http://www.geeksforgeeks.org/minimum-number-of-jumps-to-reach-end-
of-a-given-array/
*/
public class MinJumpToReachEnd {
public int minJump(int arr[],int result[]){
return jump[jump.length-1];
}
/**
* https://leetcode.com/problems/jump-game-ii/
*/
public int jump(int[] nums) {
if (nums.length == 1) {
return 0;
}
int count = 0;
int i = 0;
while (i + nums[i] < nums.length - 1) {
int maxVal = 0;
int maxValIndex = 0;
for (int j = 1; j <= nums[i]; j++) {
if (nums[j + i] + j > maxVal) {
maxVal = nums[j + i] + j;
maxValIndex = i + j;
}
}
i = maxValIndex;
count++;
}
return count + 1;
}
package com.interview.dynamic;
import java.util.List;
/**
* Given a triangle, find the minimum path sum from top to bottom.
Each step you may move to adjacent numbers on
* the row below.
* https://leetcode.com/problems/triangle/
*/
public class MinimumTriangleSum {
public int minimumTotal(List<List<Integer>> triangle) {
int n = triangle.size();
int[] dp = new int[n];
package com.interview.dynamic;
import java.util.*;
/**
* Date 10/19/2016
* @author Tushar Roy
*
* Given a positive integer n, find the least number of perfect square
numbers (for example, 1, 4, 9, 16, ...) which sum to n.
* For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n
= 13, return 2 because 13 = 4 + 9.
*
* Solution 1 - Using DP similar to coin change problem with infinite
supply
* Solution 2 - Using a BFS. Put all perfect squares in queue. Then
considering each as a node try adding
* another perfect square and see if we can get n. Keep doing this in
BFS fashion till you hit the number.
*
* https://leetcode.com/problems/perfect-squares/
*/
public class MinimumNumberOfPerfectSquares {
public int numSquaresUsingDP(int n) {
int count = (int)Math.ceil(Math.sqrt(n));
T[0] = 0;
package com.interview.dynamic;
/**
* http://www.geeksforgeeks.org/find-the-minimum-cost-to-reach-a-
destination-where-every-station-is-connected-in-one-direction/
*/
public class MinimumCostTrainTicket {
package com.interview.dynamic;
/**
* http://www.geeksforgeeks.org/dynamic-programming-set-6-min-cost-
path/
*/
public class MinCostPath {
package com.interview.dynamic;
/**
* Date 11/03/2016
* @author Tushar Roy
*
* Find maximum sum for non adjacent elements.
* Variation is finding maximum sum non adjacent elements assuming its
a circular array.
* So first element cannot be with last element.
*
* Time complexity O(n)
* Space complexity O(1)
*
* https://leetcode.com/problems/house-robber/
* https://leetcode.com/problems/house-robber-ii/
*/
public class MaxSumForNonAdjacentElements {
/**
* Fast DP solution.
*/
public int maxSum(int arr[]) {
int excl = 0;
int incl = arr[0];
for (int i = 1; i < arr.length; i++) {
int temp = incl;
incl = Math.max(excl + arr[i], incl);
excl = temp;
}
return incl;
}
/**
* Recursive slow solution.
*/
public int maxSum(int arr[], int index) {
if (index == 0) {
return arr[0];
} else if (index == 1) {
return Math.max(arr[0], arr[1]);
}
return Math.max(this.maxSum(arr, index - 2) + arr[index],
this.maxSum(arr, index - 1));
}
/**
* Find maximum sum from left to right ignoring first element.
* Find maximum sum from right to left ignoring last element.
* Maximum of two will be the answer. It gurantees that both first
and last element
* will be not selected together.
*/
public int maxSumCircularArray(int[] nums) {
if (nums.length == 0) {
return 0;
}
if (nums.length == 1) {
return nums[0];
}
int with = nums[1];
int without = 0;
for (int i = 2; i < nums.length; i++) {
int newWith = without + nums[i];
without = with;
with = Math.max(with, newWith);
}
}
}
/**
* Problem Statement:
*
* Given an array of n positive integers. Write a program to find the
sum of maximum sum subsequence of the given array
* such that the integers in the subsequence are in increasing order.
*
*
* Video: https://youtu.be/99ssGWhLPUE
*
* Reference:
* http://www.geeksforgeeks.org/dynamic-programming-set-14-maximum-
sum-increasing-subsequence/
*/
public class MaximumSumSubsequence {
package com.interview.dynamic;
/**
* http://www.geeksforgeeks.org/maximum-size-sub-matrix-with-all-1s-
in-a-binary-matrix/
*/
public class MaximumSizeSubMatrix {
int arr[][] =
{{0,1,1,0,1},{1,1,1,0,0},{1,1,1,1,0},{1,1,1,0,1}};
MaximumSizeSubMatrix mssm = new MaximumSizeSubMatrix();
int result = mssm.maxSize(arr);
System.out.print(result);
}
package com.interview.dynamic;
import com.interview.stackqueue.MaximumHistogram;
/**
* Date 06/23/2014
* @author tusroy
*
* Video link - https://youtu.be/2xvJ41-hsoE
*
* Given a 2D matrix of 0s and 1s. Find largest rectangle of all 1s
* in this matrix.
*
* Maintain a temp array of same size as number of columns.
* Copy first row to this temp array and find largest rectangular area
* for histogram. Then keep adding elements of next row to this temp
* array if they are not zero. If they are zero then put zero there.
* Every time calculate max area in histogram.
*
* Time complexity - O(rows*cols)
* Space complexity - O(cols) - if number of cols is way higher than
rows
* then do this process for rows and not columns.
*
* References:
* http://www.careercup.com/question?id=6299074475065344
*/
public class MaximumRectangularSubmatrixOf1s {
package com.interview.dynamic;
/**
* http://www.geeksforgeeks.org/dynamic-programming-set-36-cut-a-rope-
to-maximize-product/
*/
public class MaximumProductCutting {
package com.interview.dynamic;
import java.util.Arrays;
/**
* http://www.geeksforgeeks.org/dynamic-programming-set-20-maximum-
length-chain-of-pairs/
*/
public class MaximumLengthChainPair {
int max =0 ;
for(int i=1; i <T.length; i++){
if(max < T[i]){
max = T[i];
}
}
return max;
}