Dynammic Programming
Dynammic Programming
Internship Round-4
Discussion
Approach
The states of dp will be
1. N
2. Number of times the number 4 occurred
Firstly, there is no sense to items being greater than N, as this will never give the
optimal answer. If k > N, then we are buying more items than necessary.
Since we have only 3 options, whether to buy, sell or do nothing,
So, our equation will be
(do nothing) (buy the item on that day)
F(index, items) = F(index+1, items) + F(index + 1, items + 1) – prices[index]
+ F(index + 1, items - 1) + prices[index]
(sell the item on that day)
Solution : https://pastebin.com/Q89wCn5g
Approach
This is a Knapsack question!
We have to make 2 disjoint subsequences. We will try to make both simultaneously
since we only need to find the maximum length.
So, for each character of the string, we are asking whether to
1. Send it to non-decreasing subsequence
2. Send it to non-increasing subsequence
3. Do nothing with it
Equation will be
F(i, j) = F(i+1, j) + F(i+1, j+1) if s[i] = t[j], where s is our given string and t is the
constructed palindromic string of length K
Approach
It’s a knapsack variation.
The states of dp will be
1. Index (i)
2. Count (j)
dp[i][j] = no of ways to do exactly j removals after visiting starting i
elements.
Base Condition: dp[0][0] = 1.
dp[i][j] = dp[i – 1][j] (not picking)
If we can remove the segment [i – m + 1........ i] then only we can
increase the count [picking condition].
i.e. dp[i][j] = dp[i – m][j - 1] (picking)
score[2] + c + bbbcd + c
score[2] + c + bbb + cd + c
So we will take another state count, which represents the length we have considered till
now.
Now our equation will be: