Dynamic Programming: Coding Competition
Dynamic Programming: Coding Competition
DYNAMIC PROGRAMMING
O( 2^n ) > O( N )
Lets see how this idea can help us to solve lots of problems.
Dynamic Programming:
Method of solving a complex problem by breaking it down
into a collection of simpler sub problems.
Solving each of these sub problems just once and storing
their solutions.
Fibonacci Number:
Recursion + Memoization
Time Complexity: O( N )
Dynamic Programming:
Features:
1. Optimal Substructure
2. Overlapping subproblem
Optimal solution to a bigger problem You can see, there is some sub
can actually be constructed using problems being computed multiple
optimal solutions to smaller problem. number of times.
Dynamic Programming Problems:
• Climbing Stairs Problem
Amazon, Intel, Morgan Stanley, LinkedIn, Snapdeal
n Case 1:
# of ways=1 Case 3:
II
I
Case 2: # of ways=2
ith (i+1)th
F[4]=3
F[5]=5
F[6]=8
N=8
i c Return P
0 1 c=n=1 1
1 2 c=n=2 1
2 3 Fib(2)+Fib(1) 2
1+1
3 4 Fib(3)+Fib(2) 3
{{Fib(2)+Fib(1)}+Fib(2)}
{{1+1}+1}
7 8 Fib(7)+Fib(6) 21
{{Fib(6)+Fib(5)}+
{Fib(5)+Fib(4) }}
{13+8}
N=8
i c F[ 0,1,2,3,4,5,6,7,8] P
0 1 0 1 -1 -1 -1 -1 -1 -1 1
1 2 0 1 -1 -1 -1 -1 -1 -1 1
2 3 0 1 1 -1 -1 -1 -1 -1 2
3 4 0 1 1 2 -1 -1 -1 -1 3
References
1. https://www.youtube.com/watch?v=gwaGGkRfcOg&list=PLLhBy6YSIT0Dg3Gl
nTQ_AtBRYNyZBQDQP&index=1
2. https://www.sanfoundry.com/dynamic-programming-problems-solutions/
3. https://www.codesdope.com/course/algorithms-dynamic-programming/