Link: https://leetcode.com/problems/painting-the-walls/
Solution:
DSA: DP, DFS, subsequence
Intuition
This seems like a heap problem, but its not. The reason why it’s not is because there is not an optimal way to use the paid painter and the free painter. It seems like you can use a min_heap for the paid painter and max_heap for the paid painter…but there are edge cases where this does no work. There are cases where choosing a higher cost/time wall is more optimal for the paid painter because its also about making sure the paid painter is working whenever the paid painter is!
For example:
So now that the heap strategy has been invalidated, lets talk about how to actually solve this problem.
It boils down to this insight: for every wall that we assign to the paid painter, the free painter can paint time[i]
walls. We don’t actually care which walls the free painter paints, because we can choose a min subsequence of walls, such that the number of walls painted is greater or equal to the total number of walls.
For example:
Implementation
Visual
Review 1
I misread the problem and thought we were solving for minimum time and found a DP solution there. The actual problem here is requires solving for min cost! I comes down to the following:
We can either incur the cost of painting the wall and then recruit our free painter, or we can not do anything with the hopes that the free painter will get to that wall at some point when we do chose to incur cost.
For example:
cost = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
time = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 100]
In the above case, we can see that it make sense to wait until the last wall to incur the cost, because that last wall takes 100 units of time which means that our free painter can paint 100 walls. We only need 12 walls painted, so since 101 (including the wall painted by our paid painter) is greater than 12, all walls have been painted at a cost of 1.
Essentially we are looking for the subsequence that reaches num_walls the cheapest. The walls don't have to be painted in any particular order so subsequence works here.