Heyo! If you tried to solve problem D you have probably ended up trying to optimize this algorithm:
But of course this won't work! The number of values in dp[i]
will grow exponentially. But we only need to output first K values of the final dp[0]
. Can we do better?
We only need to store first K values for each dp[i]
. So we can rewrite: dp[i] = cur; while (dp[i].size() > k) dp[i].pop_back();
This leaves us with O(n^2 k) solution, this time the bottleneck is the merging part. The OFFICIAL solution is to use priority queue to select first K values after merging, without going through all values. But we are not interested in that!
LAZY merging
If you have heard about Haskell, you might know that it's a lazy language, it only computes things when it absolutely needs them -- e.g. when you print them. Could it be the case that just switching our programming language to Haskell make the solution pass? (Spoiler: yes, kindof)