I've been trying to solve the DP section of CSES problemset and I noticed that usually the problems give TLE verdict if we're solving the problems using recursive DP. Am I doing something wrong, or the time limit is actually really strict?
Here is my solution for the problem Book Shop. Is there any way I can make my recursive solution faster?
Spoiler
HINT :
Relate it with Knapsack(classical) and you are good to go.
Recursive DP works with memoization (that too if time complexity is permitted).
I have actually solved it with Knapsack, but the problem is even with memoization the recursive solution is too slow (gets TLE on 2 of the testcases), but iterative solution works fine.
Instead of using m x n 2D array use 2 x n array
REFER THIS FROM Gfg =>https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/
int knapSack(int W, int wt[], int val[], int n) {
}
// Driver Code int main() { int val[] = { 60, 100, 120 }; int wt[] = { 10, 20, 30 }; int W = 50; int n = sizeof(val) / sizeof(val[0]);
}
THe space u r taking is of order of 10^8 which is indeed the reason for time complexity .Try using 2 x n 2D array instead
Refer to my code for more clarification Link: https://cses.fi/paste/2af885b03126b6a436292e/
How is it relevant? In the end, the time complexity is O(n*x)
https://cses.fi/paste/c106d1a30a05424036e90d/
Well, the constraints are a bit tight, but recursion in itself slower than iteration in case of CPP Refer here