Showing posts with label Dynamic programming. Show all posts
Showing posts with label Dynamic programming. Show all posts

Thursday, 8 June 2017

Subset Sum Problem | Dynamic Programming

Given an array of non-negative integers, and a value sum, determine if there is a subset of the given set with a sum equal to given sum and find out that subset.

Examples:
Input:
array [] = {3, 12, 4, 12, 5, 2}
sum = 7
Output:
true


package com.dp;
public class SubsetSumProblem {

     private static boolean isSumSubsetExist(int[] array, int sum) {
           int col = sum+1;
           int row = array.length+1;
           boolean[][] dp = new boolean[row][col];
          
           for(int i=0;i<row;i++) {
                dp[i][0] = true;
           }
          
           for(int i=1;i<col;i++) {
                dp[0][i] = false;
           }
          
           for (int i = 1; i < row; i++) {
                int value = array[i-1];
                /* Create DP. */
                for (int j = 1; j < col; j++) {
                     if(j<value) {
                           dp[i][j] = dp[i-1][j];
                     } else {
                           dp[i][j] = dp[i-1][j-value];
                     }
                }
           }
          
           /** Print the elements set. */
           printElements(dp, array, row, col);
          
           return dp[row-1][col-1];
     }
    
     private static void printElements(boolean[][] dp, int[] array, int row, int col) {
           int i = row-1; int j = col-1;
          
           while(i>0 && j>=0) {
                int value = array[i-1];
                if(j-value>=0 && dp[i-1][j-value]) {
                     i = i -1;
                     j = j-value;
                     System.out.println(value);
                } else {
                     i--;
                }   
           }
     }

     /**
      * Driver Method
      * @param args
      */
     public static void main(String[] args) {
           int[] array = {3, 12, 4, 12, 5, 2};
           int sum = 7;
           boolean isExist = isSumSubsetExist(array,sum);
           System.out.println(isExist);
     }
}

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.


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);
     }
}
Related Posts Plugin for WordPress, Blogger...