While I was solving this problem, I noticed that you could switch the order of the loops using the dynamic programming solution. However, when you iterate through all the weights first and then the books, you TLE. If you iterate through the books and then the weights, you get the correct answer. Why is this?
I read from this thread;
that it is because of memory. However, don’t both solutions use the same amount of memory? Also, as a side question to the first, in most dp problems, you can flip the loops as long as you have taken the necessary precautions. My question is when do we know when to use each ordering of the loops?
I still don’t understand because I flipped the rows and columns of the dp array as the blog post suggested. I still got TLE. Is there anything else that I am getting incorrect?
I believe the first solution makes \Theta(\frac{NX}{B}) L1 cache replacements, where B=64\text{ bytes} is the cache line size (proportional the number of consecutive array elements that you can read from main memory into the cache at the same time), while the second makes \Theta(NX) L1 cache replacements.
As the first solution processes consecutive j in order, it only needs to read in a new cache line after every \approx B values of j. Whereas the second would need to read a new cache line after every iteration of i because N is pretty large. As L1 cache is only ~64 KB large, you can’t fit N cache lines into memory at the same time; so if you access dp[1][j], dp[2][j], \ldots, dp[N][j], dp[1][j+1] in that order the cache line containing dp[1][j] will already have been evicted from L1 cache when you access dp[1][j+1].
EDIT: Actually N isn’t that large (I originally thought it was 10^5 instead of 10^3), but I think this reasoning still applies.
As for the third solution I think the number of cache misses is still \Theta(NX).
You can find some more information about analysis of cache misses here (might not be that beginner-friendly though).
Btw the “AC” solution doesn’t compile …
EDIT: Nvm it seems fine, maybe it was just a glitch on my end.