DP + Greedy
DP + Greedy
BY
Shubhang Walavalkar
Sanjay Bhat
Tarun Joshi
Greedy Algorithms
Given a set of items, each with a weight and a value, determine the maximum amount of
value obtained by putting items in the knapsack (fractions are allowed) such that the
total weight of the items doesn't exceed the maximum limit of the knapsack.
Greedy Strategy : Choose the item with the max value of
profit/weight ratio first. Why max ? because we want
profit to be max and weight to be min.
Proof:
https://courses.cs.duke.edu/spring19/compsci330/lectu
re8scribe.pdf
Few more problems:
1)https://codeforces.com/problemset/problem/1343/C
2) https://cses.fi/problemset/task/1074
3) https://codeforces.com/problemset/problem/1539/C
4) https://codeforces.com/contest/1154/problem/D
1D - DP
Fibonacci
Time complexity:
O(ϕ^n) or O(1.618^n)
ϕ^n is tight upper bound which can be calculated by using mathematically represented linear
recursive function
refer :
1. https://www.geeksforgeeks.org/time-complexity-recursive-fibonacci-program/
2. https://www.quora.com/What-is-the-time-complexity-of-calculating-Fibonacci-numbers-using-recursion
T(n) = T(n-1) + T(n-2) + O(1)
On solving the above recursive equation we get the upper bound of Fibonacci as O(2^n) but
this is not the tight upper bound.
from 2666ms it reduced to 4ms
Recursive VS Recursive DP
TIMED_OUT > 5s
5MS
HW Problems :)
1. https://bit.ly/3JPcoOx
2. https://bit.ly/3q5rlUY
3. https://bit.ly/3F4yl8z (2d dp)
4. CSES DP problem set
Minimizing Coin
Problem statement:
You are given an array of ‘N’ distinct integers and an integer ‘X’ representing the target
sum. You have to tell the minimum number of elements you have to take to reach the
target sum ‘X’.
A Greedy solution will be to take the highest denomination coin first, so we will take an item on
index 0, with a value of 9. Now the remaining target sum will be 2. Therefore we can only
consider coins with a value of 1. We will take 2 coins of value 1 to meet the target. So a greedy
solution gives us the answer 3 {9,1,1}
Now we can clearly see that a non-greedy solution of taking 2 coins valued 6 and 5 will give us
a better option. So we can say that the greedy solution doesn’t work for this problem.
BASE case: Recursive way
if target ==0:
return 0;
Using 1D-DP ,
Memoization