You are given two 0-indexed integer arrays, cost and time, of size n representing the costs and the time taken to paint n different walls respectively. There are two painters available:
- A paid painter that paints the
ithwall intime[i]units of time and takescost[i]units of money. - A free painter that paints any wall in
1unit of time at a cost of0. But the free painter can only be used if the paid painter is already occupied.
Return the minimum amount of money required to paint the n walls.
Example 1:
Input: cost = [1,2,3,2], time = [1,2,3,2] Output: 3 Explanation: The walls at index 0 and 1 will be painted by the paid painter, and it will take 3 units of time; meanwhile, the free painter will paint the walls at index 2 and 3, free of cost in 2 units of time. Thus, the total cost is 1 + 2 = 3.
Example 2:
Input: cost = [2,3,4,2], time = [1,1,1,1] Output: 4 Explanation: The walls at index 0 and 3 will be painted by the paid painter, and it will take 2 units of time; meanwhile, the free painter will paint the walls at index 1 and 2, free of cost in 2 units of time. Thus, the total cost is 2 + 2 = 4.
Constraints:
1 <= cost.length <= 500cost.length == time.length1 <= cost[i] <= 1061 <= time[i] <= 500
Companies: Amazon, Adobe, Snowflake, Apple
Related Topics:
Array, Dynamic Programming
Hints:
- Can we break the problem down into smaller subproblems and use DP?
- Paid painters will be used for a maximum of N/2 units of time. There is no need to use paid painter for a time greater than this.
Let dp[k] be the minimum cost to finish k walls.
Initially
dp[0] = 0
dp[k>0] = inf
For ith wall, we update dp[j] with this dp equation
dp[j] = min(dp[j], dp[max(j - time[i] - 1, 0)] + cost[i])
If we paint ith wall, we increase cost by cost[i], and we can paint time[i] more walls with free painters. So, we can paint time[i] + 1 walls with this choice. Thus, we can try to use dp[max(j - time[i] - 1, 0)] + cost[i] to update dp[j].
// OJ: https://leetcode.com/problems/painting-the-walls
// Author: github.com/lzl124631x
// Time: O(N^2)
// Space: O(N)
// Ref: https://leetcode.com/problems/painting-the-walls/solutions/3650707/java-c-python-7-lines-knapsack-dp/
class Solution {
public:
int paintWalls(vector<int>& cost, vector<int>& time) {
int n = cost.size();
vector<int> dp(n + 1, 1e9);
dp[0] = 0;
for (int i = 0; i < n; ++i)
for (int j = n; j > 0; --j)
dp[j] = min(dp[j], dp[max(j - time[i] - 1, 0)] + cost[i]);
return dp[n];
}
};