Advertisement
mjain

DP

Jul 12th, 2019
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 17.02 KB | None | 0 0
  1. package testrun;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Arrays;
  5. import java.util.Stack;
  6.  
  7. public class DynamicProgrammingProblem {
  8.  
  9.     public static ArrayList<Integer[]> diskStacking(ArrayList<Integer[]> disks) {
  10.         ArrayList<Integer[]> retList = new ArrayList<Integer[]>();
  11.         // sort disk List by height
  12.         disks.sort((d1, d2) -> d1[2].compareTo(d2[2]));
  13.         // heights array to store max height upto that index;
  14.         int[] heights = new int[disks.size()];
  15.         for (int i = 0; i < disks.size(); i++) {
  16.             heights[i] = disks.get(i)[2];
  17.         }
  18.         // sequence array to manintain the last max height index for each entry
  19.         int[] seq = new int[disks.size()];
  20.         Arrays.fill(seq, Integer.MIN_VALUE);
  21.  
  22.         // maintain the index for index at max height
  23.  
  24.         int maxHeighIndex = 0;
  25.         for (int i = 1; i < disks.size(); i++) {
  26.             Integer[] currentDisk = disks.get(i);
  27.             for (int j = 0; j < i; j++) {
  28.                 Integer[] otherDisk = disks.get(j);
  29.                 // check all valid dimensions
  30.                 if (otherDisk[0] < currentDisk[0] && otherDisk[1] < currentDisk[1] && otherDisk[2] < currentDisk[2]) {
  31.                     if (heights[i] < heights[j] + currentDisk[2]) {
  32.                         heights[i] = heights[j] + currentDisk[2];
  33.                         seq[i] = j;
  34.                     }
  35.                 }
  36.             }
  37.             if (heights[i] > heights[maxHeighIndex]) {
  38.                 maxHeighIndex = i;
  39.             }
  40.         }
  41.         while (maxHeighIndex != Integer.MIN_VALUE) {
  42.             retList.add(0, disks.get(maxHeighIndex));
  43.             maxHeighIndex = seq[maxHeighIndex];
  44.         }
  45.         System.out.print(retList);
  46.         return retList;
  47.     }
  48.  
  49.     public static ArrayList<ArrayList<Integer>> knapsackProblem(int[][] items, int capacity) {
  50.         ArrayList<ArrayList<Integer>> returnList = new ArrayList<ArrayList<Integer>>();
  51.         if (capacity <= 0) {
  52.             ArrayList<Integer> l = new ArrayList<Integer>();
  53.             l.add(0);
  54.             returnList.add(l);
  55.             returnList.add(new ArrayList<Integer>());
  56.             return returnList;
  57.         }
  58.  
  59.         int n = items.length + 1;
  60.         int dpMat[][] = new int[n][capacity + 1];
  61.  
  62.         for (int i = 1; i < n; i++) {
  63.             int curItem = items[i - 1][0];
  64.             int curWeight = items[i - 1][1];
  65.             for (int j = 0; j <= capacity; j++) {
  66.                 if (curWeight <= j) {
  67.                     dpMat[i][j] = Math.max(curItem + dpMat[i - 1][j - curWeight], dpMat[i - 1][j]);
  68.                 } else {
  69.                     dpMat[i][j] = dpMat[i - 1][j];
  70.                 }
  71.             }
  72.         }
  73.  
  74.         int weight = dpMat[n - 1][capacity];
  75.         ArrayList<Integer> l = new ArrayList<Integer>();
  76.         l.add(weight);
  77.         returnList.add(l);
  78.         returnList.add(new ArrayList<Integer>());
  79.         int i = dpMat.length - 1;
  80.         int c = dpMat[0].length - 1;
  81.         while (i > 0) {
  82.             if (dpMat[i][c] == dpMat[i - 1][c]) {
  83.                 i--;
  84.             } else {
  85.                 returnList.get(1).add(0, i - 1);
  86.                 c = c - items[i - 1][1];
  87.                 i--;
  88.  
  89.             }
  90.             if (c == 0) {
  91.                 break;
  92.             }
  93.  
  94.         }
  95.  
  96.         System.out.print(returnList);
  97.         return returnList;
  98.     }
  99.  
  100.     public static class Box implements Comparable<Box> {
  101.         int l, b, h, area;
  102.  
  103.         public Box(int l, int b, int h) {
  104.             super();
  105.             this.l = l;
  106.             this.b = b;
  107.             this.h = h;
  108.         }
  109.  
  110.         @Override
  111.         public int compareTo(Box b) {
  112.             return b.area - this.area;
  113.         }
  114.     }
  115.  
  116.     public static int getMaxHeightFromBoxStack(Box[] boxes, int n) {
  117.         Box[] sortedBox = new Box[n * 3];
  118.         for (int i = 0; i < n; i++) {
  119.             Box box = boxes[i];
  120.             sortedBox[3 * i] = new Box(box.h, Math.max(box.l, box.b), Math.min(box.l, box.b));
  121.             sortedBox[3 * i + 1] = new Box(box.l, Math.max(box.h, box.b), Math.min(box.h, box.b));
  122.             sortedBox[3 * i + 2] = new Box(box.b, Math.max(box.l, box.h), Math.min(box.l, box.h));
  123.         }
  124.         for (int i = 0; i < sortedBox.length; i++) {
  125.             sortedBox[i].area = sortedBox[i].l * sortedBox[i].b;
  126.         }
  127.         Arrays.sort(sortedBox);
  128.         int count = 3 * n;
  129.         int[] msh = new int[count];
  130.         for (int i = 0; i < count; i++) {
  131.             msh[i] = sortedBox[i].h;
  132.         }
  133.  
  134.         for (int i = 1; i < n; i++) {
  135.             msh[i] = 0;
  136.             Box box = sortedBox[i];
  137.             int val = 0;
  138.             for (int j = 0; j < i; j++) {
  139.                 Box prevBox = sortedBox[j];
  140.                 if (box.l < prevBox.l && box.b < prevBox.b) {
  141.                     val = Math.max(val, msh[j]);
  142.                 }
  143.             }
  144.             msh[i] = val + box.h;
  145.         }
  146.         int max = -1;
  147.  
  148.         /* Pick maximum of all msh values */
  149.         for (int i = 0; i < count; i++) {
  150.             max = Math.max(max, msh[i]);
  151.         }
  152.  
  153.         return max;
  154.     }
  155.  
  156.     public static ArrayList<ArrayList<Integer>> maxSumIncreasingSubsequence(int[] array) {
  157.         ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
  158.         int sequenceOfMaxSum[] = new int[array.length];
  159.         Arrays.fill(sequenceOfMaxSum, Integer.MIN_VALUE);
  160.         int sum[] = new int[array.length];
  161.         sum = array.clone();
  162.         int maxSumIndex = 0;
  163.         for (int i = 0; i < array.length; i++) {
  164.             for (int j = 0; j < i; j++) {
  165.                 if (array[i] > array[j] && sum[j] + array[i] >= sum[i]) {
  166.                     sum[i] = sum[j] + array[i];
  167.                     sequenceOfMaxSum[i] = j;
  168.                 }
  169.             }
  170.             if (sum[i] > sum[maxSumIndex]) {
  171.                 maxSumIndex = i;
  172.             }
  173.         }
  174.  
  175.         list.add(new ArrayList<Integer>());
  176.         list.add(new ArrayList<Integer>());
  177.         list.get(0).add(sum[maxSumIndex]);
  178.         while (maxSumIndex != Integer.MIN_VALUE) {
  179.             list.get(1).add(0, array[maxSumIndex]);
  180.             maxSumIndex = sequenceOfMaxSum[maxSumIndex];
  181.         }
  182.  
  183.         // System.out.print(list);
  184.         return list;
  185.     }
  186.  
  187.     public static int minNumberOfJumps(int[] arr) {
  188.         if (arr.length <= 1)
  189.             return 0;
  190.  
  191.         // Return -1 if not possible to jump
  192.         if (arr[0] == 0)
  193.             return -1;
  194.  
  195.         // initialization
  196.         int maxReach = arr[0];
  197.         int step = arr[0];
  198.         int jump = 1;
  199.  
  200.         // Start traversing array
  201.         for (int i = 1; i < arr.length; i++) {
  202.             // Check if we have reached the end of the array
  203.             if (i == arr.length - 1)
  204.                 return jump;
  205.  
  206.             // updating maxReach
  207.             maxReach = Math.max(maxReach, i + arr[i]);
  208.  
  209.             // we use a step to get to the current index
  210.             step--;
  211.  
  212.             // If no further steps left
  213.             if (step == 0) {
  214.                 // we must have used a jump
  215.                 jump++;
  216.  
  217.                 // Check if the current index/position or lesser index
  218.                 // is the maximum reach point from the previous indexes
  219.                 if (i >= maxReach)
  220.                     return -1;
  221.  
  222.                 // re-initialize the steps to the amount
  223.                 // of steps to reach maxReach from position i.
  224.                 step = maxReach - i;
  225.             }
  226.         }
  227.         return -1;
  228.     }
  229.  
  230.     public static void main(String[] args) {
  231.         // int n = getFibonacciNo(4);
  232.         // System.out.print("Fabonacci " + n);
  233.         // coinChangeProblem();
  234.         // largestRectangleArea();
  235.         // longestCommonSubsequence("ABCDEFG", "APPLES");
  236.         // int[] input = { 8, 12, 2, 3, 15, 5, 7 };
  237.         // maxSumIncreasingSubsequence(input);
  238.         // int[][] input = { { 1, 2 }, { 4, 3 }, { 5, 6 }, { 6, 7 } };
  239.         // knapsackProblem(input, 10);
  240.  
  241.         ArrayList<Integer[]> input = new ArrayList<Integer[]>();
  242.         input.add(new Integer[] { 2, 1, 2 });
  243.         input.add(new Integer[] { 3, 2, 3 });
  244.         input.add(new Integer[] { 2, 2, 8 });
  245.         input.add(new Integer[] { 2, 3, 4 });
  246.         input.add(new Integer[] { 2, 2, 1 });
  247.         input.add(new Integer[] { 4, 4, 5 });
  248.         diskStacking(input);
  249.     }
  250.  
  251.     public static int getFibonacciNo(int n) {
  252.         if (n == 0) {
  253.             return 0;
  254.         }
  255.         if (n == 1) {
  256.             return 1;
  257.         }
  258.         int f[] = new int[n + 2];
  259.         f[0] = 0;
  260.         f[1] = 1;
  261.         for (int i = 2; i <= n; i++) {
  262.             f[i] = f[i - 1] + f[i - 2];
  263.         }
  264.         return f[n];
  265.     }
  266.  
  267.     // https://www.geeksforgeeks.org/gold-mine-problem/
  268.     public static void goldMineProblem() {
  269.         int goldMine[][] = { { 1, 3, 1, 5 }, { 2, 2, 4, 1 }, { 5, 0, 2, 3 }, { 0, 6, 1, 2 } };
  270.         int m = 4, n = 4;
  271.         int minerTable[][] = new int[m][n];
  272.         for (int[] rows : minerTable) {
  273.             Arrays.fill(rows, 0);
  274.         }
  275.         for (int column = n - 1; column >= 0; column--) {
  276.             for (int row = 0; row < m; row++) {
  277.                 // gold collected at right move,If at last column gold collected
  278.                 // will be zero,other wise it will be same row next column
  279.                 int rightCost = (column == n - 1) ? 0 : minerTable[row][column + 1];
  280.                 // gold collected at right up,If first row or last column gold
  281.                 // collected will be zero.other wise previous row,next column
  282.                 int rightUpwords = (row == 0 || column == n - 1) ? 0 : minerTable[row - 1][column + 1];
  283.                 // gold collected at right up,If last row or last column gold
  284.                 // collected will be zero.other wise next row,next column
  285.                 int rightDown = (row == m - 1 || column == n - 1) ? 0 : minerTable[row + 1][column + 1];
  286.                 // Max gold collected from taking
  287.                 // either of the above 3 paths
  288.                 minerTable[row][column] += goldMine[row][column]
  289.                         + Math.max(rightCost, Math.max(rightUpwords, rightDown));
  290.             }
  291.         }
  292.         // The max amount of gold collected will be
  293.         // the max value in first column of all rows
  294.         int maxGoldCollected = minerTable[0][0];
  295.         for (int i = 1; i < m; i++) {
  296.             maxGoldCollected = Math.max(maxGoldCollected, minerTable[i][0]);
  297.         }
  298.         System.out.println("Max gold collected by minor: " + maxGoldCollected);
  299.     }
  300.  
  301.     public static void coinChangeProblem() {
  302.         int coins[] = { 1, 2, 3 };
  303.         int amount = 5;
  304.         int noOfWays[][] = new int[coins.length + 1][amount + 1];
  305.  
  306.         // if amount=0 then just return empty set to make the change
  307.         for (int val = 0; val < coins.length; val++) {
  308.             noOfWays[val][0] = 1;
  309.         }
  310.         // if no coins given, 0 ways to make the amount
  311.         for (int i = 1; i <= amount; i++) {
  312.             noOfWays[0][i] = 0;
  313.  
  314.         }
  315.         for (int i = 1; i <= coins.length; i++) {
  316.             for (int j = 1; j <= amount; j++) {
  317.                 // check if the coin value is less than the amount needed
  318.                 if (coins[i - 1] <= j) {
  319.                     // reduce the amount by coin value and
  320.                     // use the subproblem solution (amount-v[i]) and
  321.                     // add the solution from the top to it
  322.                     noOfWays[i][j] = noOfWays[i][j - coins[i - 1]] + noOfWays[i - 1][j];
  323.                 } else {
  324.                     // just copy the value from the top
  325.                     noOfWays[i][j] = noOfWays[i - 1][j];
  326.                 }
  327.             }
  328.         }
  329.         System.out.print("No OF ways:" + noOfWays[coins.length][amount]);
  330.  
  331.         // o(n) space solution
  332.  
  333.         int table[] = new int[amount + 1];
  334.         table[0] = 1;
  335.  
  336.         for (int i = 0; i < coins.length; i++) {
  337.             for (int j = coins[i]; j <= amount; j++) {
  338.                 table[j] += table[j - coins[i]];
  339.             }
  340.         }
  341.         System.out.print("No OF ways:" + table[amount]);
  342.  
  343.     }
  344.  
  345.     // https://www.geeksforgeeks.org/cutting-a-rod-dp-13/
  346.  
  347.     public static void cutRodProblem(int price[], int n) {
  348.         int cost[] = new int[n + 1];
  349.         cost[0] = 0;
  350.  
  351.         for (int i = 1; i < n; i++) {
  352.             int maxVal = Integer.MIN_VALUE;
  353.             for (int j = 0; j < i; j++) {
  354.                 maxVal = Math.max(maxVal, price[j] + cost[i - j - 1]);
  355.                 cost[i] = maxVal;
  356.             }
  357.         }
  358.         System.out.print("MAx value for cutting rod: " + cost[n]);
  359.     }
  360.  
  361.     public static int largestIncreasingSeqRecursion(int[] arr, int startingindex, int length, int previousELelment) {
  362.         if (arr == null || length == 0 || startingindex == length) {
  363.             return 0;
  364.         }
  365.         int exclude = largestIncreasingSeqRecursion(arr, startingindex + 1, length, previousELelment);
  366.         int include = 0;
  367.         if (arr[startingindex] > previousELelment) {
  368.             include = 1 + largestIncreasingSeqRecursion(arr, startingindex + 1, length, arr[startingindex]);
  369.  
  370.         }
  371.         return Math.max(exclude, include);
  372.     }
  373.  
  374.     public static int LISWithMaxSum(int[] arr) {
  375.         int length = arr.length;
  376.         int[] dp = new int[length];
  377.  
  378.         for (int i = 0; i < dp.length; i++) {
  379.             dp[i] = arr[i];
  380.         }
  381.  
  382.         // start from second
  383.         for (int i = 1; i < length; i++) {
  384.             for (int j = 0; j < i; j++) {
  385.                 // if current element is greater than previous and sequence end
  386.                 // at arr[j]
  387.                 if (arr[i] > arr[j] && dp[i] < dp[j] + arr[i]) {
  388.                     dp[i] = dp[j] + arr[i];
  389.                 }
  390.             }
  391.         }
  392.         return Arrays.stream(dp).max().getAsInt();
  393.  
  394.     }
  395.  
  396.     public static int LISWithDP(int[] arr) {
  397.         int length = arr.length;
  398.         int[] dp = new int[length];
  399.         // if include current element in sequence
  400.         for (int i = 0; i < dp.length; i++) {
  401.             dp[i] = 1;
  402.         }
  403.         // start from second
  404.         for (int i = 1; i < length; i++) {
  405.             for (int j = 0; j < i; j++) {
  406.                 // if current element is greater than previous and sequence end
  407.                 // at arr[j]
  408.                 if (arr[i] > arr[j] && dp[i] < dp[j]) {
  409.                     dp[i] = dp[j] + 1;
  410.                 }
  411.             }
  412.         }
  413.         return Arrays.stream(dp).max().getAsInt();
  414.     }
  415.  
  416.     public static ArrayList<Character> longestCommonSubsequence(String str1, String str2) {
  417.         int m = str1.length();
  418.         int n = str2.length();
  419.         int[][] mat = new int[m + 1][n + 1];
  420.         for (int i = 0; i <= m; i++) {
  421.             for (int j = 0; j <= n; j++) {
  422.                 if (i == 0 || j == 0) {
  423.                     mat[i][j] = 0;
  424.                 } else if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
  425.                     mat[i][j] = mat[i - 1][j - 1] + 1;
  426.                 } else {
  427.                     mat[i][j] = Math.max(mat[i - 1][j], mat[i][j - 1]);
  428.                 }
  429.  
  430.             }
  431.         }
  432.  
  433.         ArrayList<Character> list = new ArrayList<Character>();
  434.  
  435.         int i = m;
  436.         int j = n;
  437.         while (i > 0 && j > 0) {
  438.             if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
  439.                 list.add(0, str1.charAt(i - 1));
  440.                 i--;
  441.                 j--;
  442.  
  443.             } else if (mat[i - 1][j] > mat[i][j - 1]) {
  444.                 i--;
  445.             } else {
  446.                 j--;
  447.             }
  448.         }
  449.  
  450.         return list;
  451.     }
  452.  
  453.     public static int largestRectangleArea() {
  454.         int height[] = { 1, 2, 3, 4, 5, 2, 7 };
  455.         if (height == null || height.length == 0) {
  456.             return 0;
  457.         }
  458.         Stack<Integer> stack = new Stack<Integer>();
  459.         int max = 0;
  460.         int i = 0;
  461.  
  462.         while (i < height.length) {
  463.             // push index to stack when the current height is larger than the
  464.             // previous one
  465.             if (stack.isEmpty() || height[i] >= height[stack.peek()]) {
  466.                 stack.push(i);
  467.                 i++;
  468.                 System.out.println("Stack status in first loop: " + stack.toString());
  469.             } else {
  470.                 // calculate max value when the current height is less than the
  471.                 // previous one
  472.                 int p = stack.pop();
  473.                 int h = height[p];
  474.                 int w = stack.isEmpty() ? i : i - stack.peek() - 1;
  475.                 max = Math.max(h * w, max);
  476.  
  477.                 System.out.println("Stack status in sencond loop: " + stack.toString());
  478.                 System.out.println("Max Area so far: " + max);
  479.  
  480.             }
  481.         }
  482.         while (!stack.isEmpty()) {
  483.             int p = stack.pop();
  484.             int h = height[p];
  485.             int w = stack.isEmpty() ? i : i - stack.peek() - 1;
  486.             max = Math.max(h * w, max);
  487.         }
  488.  
  489.         System.out.print("Max Area: " + max);
  490.         return max;
  491.     }
  492. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement