0% found this document useful (0 votes)
11 views7 pages

DP 2

The document covers dynamic programming (DP) concepts including limitations of top-down programming, the tabulation method, and differences between tabulation and memoization. It provides examples such as the Fibonacci sequence and various DP problems like coin change and the 0/1 knapsack problem, along with code implementations. Additionally, it discusses the frog jump problem and outlines upcoming lectures on interview problems related to DP.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views7 pages

DP 2

The document covers dynamic programming (DP) concepts including limitations of top-down programming, the tabulation method, and differences between tabulation and memoization. It provides examples such as the Fibonacci sequence and various DP problems like coin change and the 0/1 knapsack problem, along with code implementations. Additionally, it discusses the frog jump problem and outlines upcoming lectures on interview problems related to DP.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Lesson:

DP 2
Pre-requisites
What is Dynamic Programming
What are overlapping subproblems
What is an optimal substructure
Greedy vs D
Where to use dynamic programming
What are the various approaches of DP
What is memoization
Steps of solving a DP proble
Problems of Memoization

Today’s Checklist
What is the Limitation of Top-DownProgramming
What is Tabulation
How is tabulation different from memoization
Fibonacci with tabulatio
Problems of tabulation

TOPIC: What is the Limitation of Top-


DownProgramming?

Since the process starts with the big picture, it can be difficult to make changes later on in the process
Breaking down the bigger problem into smaller subproblems can take a lot of time, especially if the design
is complex
It requires massive amounts of expensive recursion.

TOPIC: What is Tabulation?


Tabulation is a bottom-up approach where we store the results of the subproblems in a table and use
these results to solve larger subproblems until we solve the entire problem
It is used when we can define the problem as a sequence of subproblems and the subproblems do not
overlap
Tabulation is typically implemented using iteration and is well-suited for problems that have a large set of
inputs.

TOPIC: How is tabulation different from


memoization?

Cracking the Coding Interview in JAVA - Foundation


Tabulation has Iterative implementation as compared to memoization which follows a recursive
implementation
Tabulation is used when the subproblems do not overlap whereas memoization is used for overlapping
subproblems
Tabulation is well-suited for problems with a large set of inputs whereas memoization is well-suited for
problems with a relatively small set of inputs.

Example: Fibonacci sequence using Tabulation


Ques: Given an integer n, find the Fibonacci sequence upto n.

Fibonacci sequence till n = 5: 0 1 1 2 3

Answer: 3

EXPLANATION:

In the bottom-up dynamic programming approach, we’ll reorganize the order in which we solve the
subproblems.

So, we start with the smallest problem and reach till the largest problem which is the given problem.

For example: We’ll compute n = 0, then n = 1 and so on till n = 5.

Let’s checkout the code using a table to store the previously computed results.

Code:

https://pastebin.com/KTqZP2iN

OUTPUT:

Now, if we see, the above approach will only allow us to compute the solution to each problem only once,
and we’ll only need to save two intermediate results at a time
For example, when we’re trying to find the answer for n = 2, we only need to have the solutions to n=1 and
n=0 available. Similarly, for n = 3, we only need to have the solutions to n = 2 and n = 1
To implement this space optimization, we make use of only two variables, and these variables store the
required 2 values at each point of iteration until we reach n
This will allow us to use less memory space in our code
This is called space-state reduction.

CODE:

https://pastebin.com/jJRPUtrT

Cracking the Coding Interview in JAVA - Foundation


OUTPUT:

TOPIC: PROBLEMS on Tabulation

Q1. Given an integer array of coins[ ] of size N representing different types of currency and an integer sum,

The task is to find the number of ways to make a sum by using different combinations from coins[]. Assume

that you have an infinite supply of each type of coin.

Input1: sum = 4, coins[] = {1,2,3}, 

Output1: 4

Explanation: there are four solutions: {1, 1, 1, 1}, {1, 1, 2}, {2, 2}, {1, 3}. 

Input: sum = 10, coins[] = {2, 5, 3, 6}

Output: 5

Explanation

The Idea to Solve this Problem is by using the Bottom Up(Tabulation). By using the linear array for space

optimization

Initialize with a linear array table with values equal to 0

With sum = 0, there is a way

Update the level wise number of ways of coin till the ith coin

Solve till j <= sum.

Code:

https://pastebin.com/jJRPUtrT

Output:

Cracking the Coding Interview in JAVA - Foundation


Q2. 0/1 KNAPSACK

We are given N items where each item has some weight and profit associated with it. We are also given a bag

with capacity W, [i.e., the bag can hold at most W weight in it]. The target is to put the items into the bag such

that the sum of profits associated with them is the maximum possible. 

Input1: 

N = 3, W = 4, profit[] = {1, 2, 3}, weight[] = {4, 5, 1}



Output1: 3



Explanation: There are two items which have weight less than or equal to 4. If we select the item with weight 4,

the possible profit is 1. And if we select the item with weight 1, the possible profit is 3. So the maximum possible

profit is 3. Note that we cannot put both the items with weight 4 and 1 together as the capacity of the bag is 4.

Input2: N = 3, W = 3, profit[] = {1, 2, 3}, weight[] = {4, 5, 6}



Output2: 0

Explanation

A simple solution is to consider all subsets of items and calculate the total weight and profit of all subsets.

Consider the only subsets whose total weight is smaller than W.

From all such subsets, pick the subset with maximum profit

To consider all subsets of items, there can be two cases for every item.

Case 1: The item is included in the optimal subset

Case 2: The item is not included in the optimal set

The maximum value obtained from ‘N’ items is the max of the following two values

Maximum value obtained by N-1 items and W weight (excluding nth item)

Value of nth item plus maximum value obtained by N-1 items and (W – weight of the Nth item) [including

Nth item]

If the weight of the ‘Nth‘ item is greater than ‘W’, then the Nth item cannot be included and Case 1 is the only

possibility

Since subproblems are evaluated again, this problem has Overlapping Sub-problems property and optimal

substructure property

Re-computation of the same subproblems can be avoided by constructing a temporary array K[][] in a

bottom-up manner.

In a DP[][] table let’s consider all the possible weights from ‘1’ to ‘W’ as the columns and the element that

can be kept as rows.

The state DP[i][j] will denote the maximum value of ‘j-weight’ considering all values from ‘1 to ith‘. So if we

consider ‘wi‘ (weight in ‘ith‘ row) we can fill it in all columns which have ‘weight values > wi‘. Now two

possibilities can take place:

Fill ‘wi‘ in the given column

Do not fill ‘wi‘ in the given column

Now we have to take a maximum of these two possibilities,

Formally if we do not fill the ‘ith‘ weight in the ‘jth‘ column then the DP[i][j] state will be the same as DP[i-1]

[j]

Cracking the Coding Interview in JAVA - Foundation


But if we fill the weight, DP[i][j] will be equal to the value of (‘wi‘+ value of the column weighing ‘j-wi’) in

the previous row.

So we take the maximum of these two possibilities to fill the current state. 

Code:

https://pastebin.com/amGZwQVE

Output:

Q3. There are N stones, numbered 1,2,…,N. The height of ith stone is hi.

There is a frog who is initially on Stone 1. He will repeat an action some number of times to reach Stone N. The

action is that if the frog is currently on Stone i, it jumps to one of the following: Stone i+1,i+2,…,i+K. Here, a cost

of |hi - hj| is incurred, where j is the stone to land on.

Find the minimum possible total cost incurred before the frog reaches Stone N. 

Input1:

n = 5 

k = 3

10 30 40 50 20


Output1:

30

Input2:

3 1

10 20 10


Output2:

20

Explanation

We create a dp array of the same length as the input array

Let's define dp[i] as the minimum cost to reach Stone i from Stone 1. Our goal is to find dp[N], which

Cracking the Coding Interview in JAVA - Foundation


represents the minimum possible total cost incurred before the frog reaches Stone N
We know that the minimum cost to reach Stone 1 from Stone 1 is 0, so we set dp[1] = 0
To calculate dp[i], we need to consider all possible jumps the frog can make from the previous stones (i-1,
i-2, ..., i-K). We choose the jump that incurs the minimum cost. Mathematically, we can express this as: dp[i]
= min(dp[i-1] + |hi - hi-1|, dp[i-2] + |hi - hi-2|, ..., dp[i-K] + |hi - hi-K|
We run 2 nested loops, the outer loop runs from 1 to n and the second loop runs from 1 to k
We initialize a pointer minn for every iteration
We check if the outer index variable is greater than or equal to inner index variable and if so, we update
minn as minimum of its current value and height difference of the two indices
Update dp of current index as minn
Return dp of n-1 in the end.

Code:

https://pastebin.com/QGT6r83E

Output:

Upcoming lectures:
Interview Problems on DP-1

Cracking the Coding Interview in JAVA - Foundation

You might also like