Popular Posts

Showing posts with label DP. Show all posts
Showing posts with label DP. Show all posts

Saturday, February 18, 2012

Matrix Chain Multiplication

Given an array p[] which represents the chain of matrices such that the ith matrix Ai is of dimension p[i-1] x p[i]. We need to write a function MatrixChainOrder() that should return the minimum number of multiplications needed to multiply the chain.
Refer : http://www.geeksforgeeks.org/archives/15553

Binomial Coefficient

Write a function that takes two parameters n and k and returns the value of Binomial Coefficient C(n, k).
The value of C(n, k) can recursively calculated using following standard formula for Binomial Cofficients.

   C(n, k) = C(n-1, k-1) + C(n-1, k)
   C(n, 0) = C(n, n) = 1

Refer : http://www.geeksforgeeks.org/archives/17806

Friday, February 17, 2012

N Queen Problem

The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other.
Refer : http://www.geeksforgeeks.org/archives/13387

Rat in a Maze

A Maze is given as N*N binary matrix of blocks where source block is the upper left most block i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1]. A rat starts from source and has to reach destination. The rat can move only in two directions: forward and down.
In the maze matrix, 0 means the block is dead end and 1 means the block can be used in the path from source to destination. Note that this is a simple version of the typical Maze problem. For example, a more complex version can be that the rat can move in 4 directions and a more complex version can be with limited number of moves.

public class RatMaze {
public static void main(String[] args) {

int[][] maze = {
{ 1, 0, 0, 0 },
{ 1, 1, 0, 1 },
{ 0, 1, 0, 0 },
{ 1, 1, 1, 1 }
};

int m = maze.length;
int n = maze[0].length;
int[][] solution = new int[m][n];

boolean isSolutionAvailable = getSolution(maze, solution, 0, 0);
if (isSolutionAvailable) {
printMatrix(solution);
} else {
System.out.println("Solution is not available");
}
}

private static void printMatrix(int[][] a) {
System.out.println();
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(" " + a[i][j] + " ");
}
System.out.println();
}
}

private static boolean getSolution(int[][] maze, int[][] solution, int i,
int j) {
int m = maze.length;
int n = maze[0].length;

if (i < 0 || i >= m || j < 0 || j >= n || maze[i][j] == 0) {//check if path is blocked
return false;
}

if (i == m - 1 && j == n - 1) {
solution[i][j] = 1;
return true;
}

// At each position look in forward and downward direction.
if (getSolution(maze, solution, i, j + 1)
|| getSolution(maze, solution, i + 1, j)) {
solution[i][j] = 1;
return true;
}
return false;
}
}

Refer : http://www.geeksforgeeks.org/archives/13376

The Knight’s tour problem

Backtracking is an algorithmic paradigm that tries different solutions until finds a solution that “works”. Problems which are typically solved using backtracking technique have following property in common. These problems can only be solved by trying every possible configuration and each configuration is tried only once. A Naive solution for these problems is to try all configurations and output a configuration that follows given problem constraints. Backtracking works in incremental way and is an optimization over the Naive solution.

For example, consider the following Knight’s Tour problem.
The knight is placed on the empty board and, moving according to the rules of chess, must visit each square exactly once.

Refer : http://www.geeksforgeeks.org/archives/12916

Thursday, February 16, 2012

Coin change

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.

For example, for N = 4 and S = {1,2,3}, there are four solutions: {1,1,1,1},{1,1,2},{2,2},{1,3}. So output should be 4. For N = 10 and S = {2, 5, 3, 6}, there are five solutions: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}. So the output should be 5.

Refer : http://www.geeksforgeeks.org/archives/17401

Monday, February 13, 2012

Dynamic programming

Here is a link points to important resources of dynamic programming :
http://avidullu.wordpress.com/2010/02/18/solution-to-dynamic-programming-problems/

Minimum number of jumps to reach last element


Problem: Given an array of integers, each element represents the max number of jumps can make forward. What is the minimum number of element selections to reach the end of the array (starting from the first element).
Example: arr = 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9
Here the min # of selections is : 3
with the sequence : 1-> 3 -> 8 ->9
First element is 1, so can only go to 3.
Second element is 3, so can make at most 3 jumps: eg to 5 or 8 or 9.
If an element is 0, then cannot make any jumps


public class MinNumberOfJumps {
private static int MAX = 23234;

public static void main(String[] args) {
int[] jumps = { 2, 3, 1, 1, 4 };
int minJumps = getMinJumps(jumps, jumps.length);

if (minJumps < MAX)
System.out
.println("Minimum number of jumps needed to reach the end of the array is : "
+ minJumps);
else
System.out.println("Cannot reach the end position of the array");
}

private static int getMinJumps(int[] jumps, int size) {
//Boundry conditions
if (jumps == null || size == 0 || jumps[0] == 0)
return MAX;

int[] dp = new int[size];
//Initialization of dp[i]
for (int i = 0; i < size; i++)
dp[i] = MAX;

dp[0] = 0;//no need to jump at first element

for (int i = 1; i < size; i++) {
for (int j = 0; j <= i; j++) {
if (jumps[j] >= (i - j)) {//check if jump is possible from j to is
if (dp[j] + 1 < dp[i]) //check if better solution available
dp[i] = dp[j] + 1;
}
}
}
return dp[size - 1];
}

}

Refer  : http://avidullu.wordpress.com/2011/01/12/dp-after-a-long-time/
http://tech-queries.blogspot.in/2011/08/find-optimal-number-of-jumps-to-reach.html

Tuesday, April 12, 2011

Street Trees


A group of trees is planted along a straight line.
KOI is planning to plant more trees so that the distance between two adjacent trees is equal for all trees.
For simplicity, each tree can only be planted on an integer coordinate.
For example, if 4 trees were originally planted on coordinates (1,3,7,13), and if KOI plants 3 more trees on coordinates (5,9,11), then the distance between two adjacent trees will equal for all trees.
Your task is to calculate the minimal number of trees that KOI can plant so that the distance between two adjacent trees will equal for all trees.
Input :
The first line is an integer N (3<=N<=100,000), which denotes the number of already planted trees.
The next N lines will have an integer X (1<=X<=1,000,000,000), which denotes the coordinate of each tree.
You can safely assume that the value of X will be unique.
Output :
Output the minimal number of trees that must be planted.
Example :
Input: 
4
1  3  7  13
Output:  3
Solution : Get the difference between alternate numbers into an array.Now find out the gcd of all the numbers.GCD is  the minimum distance between the trees.Start from the starting tree and keep on adding gcd to previous number.
Answer : http://www.ideone.com/Cfyr9

Restaurent problem

Yuckdonald's is considering opening a series of restaurants along
Quaint Valley Highway (QVH).The n possible locations are along a
straight line, and the distances of these locations from the start of
QVH are, in miles and in increasing order,m1;m2; : : : ;mn. The
constraints are as follows:
1)At each location,Yuckdonald's may open at most one restaurant.The
expected profi t from opening a restaurant at location i is pi, where
pi > 0 and i = 1; 2; : : : ; n.
2)Any two restaurants should be at least k miles apart, where k is a
positive integer.
Give an effi cient algorithm to compute the maximum expected total
pro fit subject to the given
constraints.

http://codepad.org/DDtJ6yBF

Longest Increasing Subsequence

Given a sequence of n real numbers A(1) ... A(n), determine a subsequence (not necessarily contiguous) of maximum length in which the values in the subsequence form a strictly increasing sequence.


http://codepad.org/C3sr0oF3

Ransom Note

Question:given an arbitrary ransom note string and another string containing all the contents of all the magazines, write a function that will return true if the ransom note can be made from the magazines; otherwise, it will return false. Remember, every letter found in the magazine string can only be used once in your ransom note. For example, if the ransom note string was "no scheme" and the magazine string was "programming interviews are weird", you would return false since you can't form the first string by grabbing and rearranging letters from the second string.


Solution is here.

Number of bus-stations

Question: At a bus-station, you have time-table for buses arrival and departure. You need to find the minimum number of platforms so that all the buses can be accommodated as per their schedule.
 Example:  Time table is like below:
Bus Arrival Departure
BusA 0900 hrs 0930 hrs
BusB 0915 hrs 1300 hrs
BusC 1030 hrs 1100 hrs
BusD 1045 hrs 1145 hrs
Then the answer must be 3. Otherwise the bus-station will not be able to accommodate all the buses.



Let’s take the same example as described above. Now we have to calculate the number of bus-station, which will be nothing but the maximum number of buses at the bus-station at any time.

So first sort all the arrival(A) and departure(D) time in an int array. Please save the corresponding arrival or departure in the array also. Either you can use a particular bit for this purpose or make a structure. After sorting our array will look like this:
0900 0915 1930 1030 1045 1100 1145 1300 
A A D A A D D D
Now modify the array as put 1 where you see A and -1 where you see D. So new array will be like this:
1 1 -1 1 1 -1 -1 -1 
And finally make a cumulative array out of this:
1 2 1 2 3 2 1 0
Your solution will be the maximum value in this array. Here it is 3.
PS: If you have a arriving and another departing at same time then put departure time first in sorted array.
Solution is here.

Count the number of ways

You have n number of chocolates. Your best friend asks for the chocolate but you say that he can take only 1 or maximum 2 chocolates at a time.

Find the number of ways in which your friend can take all the chocolates in any number of times

Answer: Starting from the base level, if we have 3 coins how many ways we could take all 3 coins if we allowed to take single or max 2 coins at once.
So it can be generalized as
no_of_ways(n) = no_of_ways(n-1) + no+_of_ways(n-2);

Monday, April 11, 2011

Apple Problem

A table composed of N*M cells,each having a certain quantity of apples, is given. you start from the upper-left corner. At each step you can go down or right one cell.Design an algorithm to find the maximum number of apples you can collect ,if you are moving from upper-left corner to bottom-right corner. 
Here is a code for solving the problem using Dynamic programming :

Java code :
public class AppleProblem {
public static void main(String[] args) {
int[][] apples = { { 2, 3, 1 }, { 4, 6, 2 }, { 7, 8, 2 } };

int rows = apples.length;
int columns = apples[0].length;

// Create a temporary array to store the maximum sum upto that position
int[][] dp = new int[rows][columns];

int prevRowValue = 0;
int prevColumnValue = 0;

for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {

if (i - 1 < 0)
prevRowValue = 0;
else
prevRowValue = dp[i - 1][j];

if (j - 1 < 0)
prevColumnValue = 0;
else
prevColumnValue = dp[i][j - 1];

dp[i][j] = apples[i][j] + max(prevRowValue, prevColumnValue);
}
}
System.out.println(dp[rows - 1][columns - 1]);
}

private static int max(int a, int b) {
return a > b ? a : b;
}
}

Tuesday, March 29, 2011

Character Combination For Numbers


Question: Suppose you represent every number with a character like
0 –> a, 1 –> b, 2 –> c, ………………24 –> y, 25 –> z

Now given a number, give words combinations for it.

Example: 1234
=> 1-2-3-4, 12-2-4, 1-23-4
=> bcde, mde, bxe

Java code for simple backtracking approach : 
public class CharCombinationWithNumbers {

private static char[] alphabet = "abcdefghijklmnopqrstyuvxyz".toCharArray();

public static void main(String[] args) {
printPossibilities("", "1234");
}

private static void printPossibilities(String partialString, String string) {
if (string == null || string.length() < 1) {
System.out.println(partialString);
return;
}
int digit = Integer.parseInt(string.substring(0, 1));
printPossibilities(partialString + alphabet[digit], string.substring(1));
if (string.length() > 1) {
digit = Integer.parseInt(string.substring(0, 2));
if (digit >= 10 && digit < alphabet.length) {
printPossibilities(partialString + alphabet[digit], string
.substring(2));
}
}
}
}


Refer : http://tech-queries.blogspot.com/2011/03/character-combination-for-numbers.html

Knapsack problem

You are given some denominations of coins in an array (int denom[])and infinite supply of all of them. Given an amount (int amount), find the minimum number of coins required to get the exact amount.


Java Code :
public class KnapSack {

private static final int MIN = 232345;

public static void main(String[] args) {
int[] v = { 34, 12 };
int amount = 2;

int coins = getMinimumNumberOfCoins(v, amount);
if (coins < MIN) {
System.out.println("Coins required are : " + coins);
} else {
System.out
.println("Cannot give denominations for the given amount");
}

int[] dp = new int[amount + 1];
for (int i = 0; i <= amount; i++) {
dp[i] = MIN;
}

coins = getMinimumNoOfCoinsDp_Recursion(v, amount, dp);
if (coins < MIN) {
System.out.println("DP : Coins required are : " + coins);
} else {
System.out
.println("DP : Cannot give denominations for the given amount");
}
}

private static int getMinimumNumberOfCoins(int[] v, int amount) {
int minimum = MIN;
if (amount == 0)
minimum = 0;
else if (amount > 0) {
for (int i = 0; i < v.length; i++) {
int temp = 1 + getMinimumNumberOfCoins(v, amount - v[i]);
if (temp < minimum)
minimum = temp;
}
}
return minimum;
}

// Dp with recursion
private static int getMinimumNoOfCoinsDp_Recursion(int[] v, int amount,
int[] dp) {

if (amount < 0)
return MIN;

if (dp[amount] < MIN)
return dp[amount];

int minimum = MIN;
dp[0] = 0;
if (amount == 0)
minimum = 0;
else if (amount > 0) {
for (int i = 0; i < v.length; i++) {
int temp = 1 + getMinimumNoOfCoinsDp_Recursion(v,
amount - v[i], dp);
if (temp < minimum)
minimum = temp;
}
}
return dp[amount] = minimum;
}
}


Dynamic programming : 
public class KnapSack {

private static final int MIN = 232345;

public static void main(String[] args) {
int[] v = { 34, 12 };
int amount = 2;

int coins = getMinimumNumberOfCoins_DP(v, amount);
if (coins < MIN) {
System.out.println("Coins required are : " + coins);
} else {
System.out
.println("Cannot give denominations for the given amount");
}
}

private static int getMinimumNumberOfCoins_DP(int[] v, int amount) {
if (amount <= 0)
System.out.println("Amount is zero");

int[] min = new int[amount + 1];
min[0] = 0;

for (int i = 1; i <= amount; i++)
min[i] = MIN;

for (int i = 1; i <= amount; i++) {
for (int j = 0; j < v.length; j++) {
if (v[j] <= i && min[i - v[j]] + 1 < min[i])
min[i] = min[i - v[j]] + 1;
}
}
return min[amount];
}
}


Refer : http://tech-queries.blogspot.com/2009/04/minimum-number-of-coins.html


0-1 knapsack problem

Max Possible Sum Of Non-Consecutive Elements

There is an integer array consisting positive numbers only. Find maximum possible sum of elements such that there are no 2 consecutive elements present in the sum.


Example: If given array is (6, 4, 2, 8, 1), the answer will be 14 (8+6). This is the maximum sum we can obtain without taking two consecutive elements.


Java Code : 
public class MaxNonConsecutiveSum {
public static void main(String[] args) {
int[] a = { 6, 4, 2, 8, 1 };
System.out.println(getMaxNonConsecutiveSum(a, 0));
System.out.println(getMaxNonConsecutiveSumDp(a));
}

private static int getMaxNonConsecutiveSum(int[] a, int pos) {
if (pos >= a.length)
return 0;

// If we include element at position 'i', we should not include position
// 'i+1'.So we start from 'i+2'
// if we don't select position 'i', then we start recurrence from i+1
return max(a[pos] + getMaxNonConsecutiveSum(a, pos + 2),
getMaxNonConsecutiveSum(a, pos + 1));
}

private static int max(int a, int b) {
return a > b ? a : b;
}

private static int getMaxNonConsecutiveSumDp(int[] a) {
if (a.length == 0)
return 0;

if (a.length == 1)
return a[0];

// create a temporary array to hold max non consecutive sums as sub
// problems'
int[] dp = new int[a.length];
dp[0] = a[0];
dp[1] = max(a[0], a[1]);
for (int i = 2; i < a.length; i++) {
dp[i] = max(dp[i - 1], dp[i - 2] + a[i]);
}
return dp[a.length - 1];
}
}


Refer : http://tech-queries.blogspot.com/2009/05/max-possible-sum-of-non-consecutive.html
http://www.geeksforgeeks.org/archives/3133 

Wednesday, March 23, 2011

Avid TV Watcher

Here is a TV avid person. He wants to spend his max time on TV. There are N channels with different program of different length and diff times. WAP so that the person can spend his max time watching TV.Precondition: If that person watches a program, he watches it completely.

Ex:
Channel1: 

prog1 – 8:00- 8:30
prog2: 9:00 – 10:00
prog3: 10:15 – 12:00

channel2: 

prg1 – 8:15 – 10:00
prg2: 10:30 – 12:00

So in this case max time will be if he watches:

ch2/prg1 + ch1/prg3



http://tech-queries.blogspot.com/2011/03/avid-tv-watcher.html

Max Downward sum

package arrays;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
* Input: 2
* 3
* 1
* 2 1
* 1 2 3
*
* 4
* 1
* 1 2
* 4 1 2
* 2 3 1 1
*
* Output: 5
* 9
*
* @author rajeevprasanna
*
*/
public class MaxDownwardSum {
public static void main(String[] args) throws NumberFormatException,
IOException {

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(in.readLine());
int n, i, j;

int[][] a = new int[100][100];

while (t-- > 0) {
n = Integer.parseInt(in.readLine());
for (i = 0; i < n; i++) {
for (j = 0; j <= i; j++) {
a[i][j] = Integer.parseInt(in.readLine());
}
}
for (i = n - 2; i >= 0; i--) {
for (j = 0; j <= i; j++) {
a[i][j] += max(a[i + 1][j], a[i + 1][j + 1]);
}
}
System.out.println(a[0][0]);
}
}

private static int max(int a, int b) {
return a > b ? a : b;
}
}