Pages

Thursday 29 December 2016

Dynamic Programming

Dynamic Programming is an algorithmic model that solves a given complex problem by breaking it down into a collection of simpler subproblems and stores the results of subproblems to avoid computing the same results again.

A problem has two below properties can be solved using Dynamic programming.

1) Overlapping subproblems
2) Optimal substructure

1) Overlapping subproblems
If the problem can be broken down into subproblems which are reused several times or a recursive algorithm for the problem solves the same subproblem over and over rather than always generating new subproblems. Computed solutions to subproblems are stored in a table so that these don’t have to recomputed.

So Dynamic Programming is not useful when there are no common (overlapping) subproblems because there is no point storing the solutions if they are not needed again.

2) Optimal substructure
A problem is said to have optimal substructure if an optimal solution of the given problem can be obtained by using optimal solutions of its subproblems. This property is used to determine the usefulness of dynamic programming and greedy algorithms for a problem.


Maximum height when coins are arranged in a triangle


public class MaxHghtToArrangeTri {
    
     /**
      *         *           ß 1 coin
      *   *         *       ß 2 coin
      * *      *          * ß 3 coin
      *
      * Coins need for Height H = 1 + 2 + 3 + ........ + H-1
      *                                 = H(H-1)/2
      * @param coins
      * @return
      */
     private static int getMaxHeight(int coins) {
          
           int d = (int)Math.pow((8*coins + 1),.5);
          
           int height = (d + 1)/2;
          
           return height-1;
     }
    
     /**
      * @param args
      */
     public static void main(String[] args) {
           int coins = 7;
           int maxHeight = getMaxHeight(coins);
          
           System.out.println(maxHeight);
     }
}

Wednesday 28 December 2016

Smallest Integer multiplication to floating number which convert it to natural

We need to find the Integer Multiplier to convert a floating number to Natural.

Input : 1.66
Output : 50

Input : 0.25
Output : 4

public class MinMulToMakeNatural {

     /**
      * Get Minimum multiplier to make Natural.
      * @param number
      * @return min mult.
      */
     private static int getMinMultiplier(float number) {
           char[] array = (number+"").toCharArray();
          
           int len = array.length;
           int numerator = array[0]- '0';
           int count = 0;
          
           boolean flag = false;
           for (inti = 1 ; i <= len-1; i++) {
                if('.'==array[i]) {
                     flag= true;
                     continue;
                }
               
                if(flag) {
                     count++;
                }
               
                int val = array[i] - '0';
                numerator = numerator * 10 + val;
           }
          
           int denominator = (int)Math.pow(10,count);
          
           int gcd = getGCD(numerator,denominator);
          
           return denominator/gcd;
     }   
    
     /**
      * @param numerator
      * @param denominator
      * @return GCD
      */
     private static int getGCD(int numerator, intdenominator) {
          
           int gcd = denominator==0?numerator:
                getGCD(denominator, numerator%denominator);
          
           return gcd;
     }

     /** Main method. */
     public static void main(String[] args) {
           float number = 1.66F;
          
           int min = getMinMultiplier(number);
          
           System.out.println("Minimum Integer Multiplier# "+min);
     }
}

Tuesday 6 December 2016

Maximum weight path ending of last row in a matrix

Find the path having the maximum weight in integer matrix [N X M].

Conditions for moves:
Path should begin from top left element and can end at any element of last row. We can move to down (i+1, j) or diagonal forward (i+1, j+1).

public class MaxWeightPathMatrix {
    
     /**
      * Moves # down or forward diagonal.
      * @param matrix
      * @return Returns the maximum weight.
      */
     private static int getMaxWeightPath(int[][] matrix) {

           int row = matrix.length;
           int col = matrix[0].length;

           int[][] dp = newint[row][col];

           /** Initialize first row of total weight */
           for(inti=0;i<col;i++) {
                dp[0][i] = matrix[0][i];
           }

           /** Initialize first column of total weight */
           for (inti=1; i<row; i++) {
                dp[i][0] = matrix[i][0] + dp[i-1][0];
           }

           for(inti=1; i<row; i++) {
                for(intj=1; j<col; j++) {
                     dp[i][j] = matrix[i][j] + Math.max(dp[i-1][j],
                                dp[i-1][j-1]);
                }
           }

           /** Max weight path sum to rech the last row */
           int result = 0;
           for (inti=0; i<col; i++) {
                result = Math.max(dp[row-1][i], result);
           }
           return result;
     }
    
     /** Driver method. */
     public static void main(String[] args) {
          
           int[][] matrix = {{ 8, 4 ,6 ,8 ,2 },
                     { 4 , 18 ,2 ,20 ,10 },
                     {20, 2 ,6 , 0 ,40 },
                     {32 ,184, 82, 88 ,2},
                     {16, 302, 12, 8, 18}};

           int maxWeight = getMaxWeightPath(matrix);

           System.out.println("Maximum weight path ending at any"
                     + " element of last row in a matrix # "+ maxWeight);
     }
}