VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-amount-to-paint-the-walls/

⇱ Minimum Amount to Paint the Walls - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum Amount to Paint the Walls

Last Updated : 23 Jul, 2025

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 ith wall in time[i] units of time and takes cost[i] units of money. A free painter that paints any wall in 1 unit of time at a cost of 0. But the free painter can only be used if the paid painter is already occupied. The task is to return the minimum amount of money required to paint the n walls.

Examples:

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.

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.

[Expected Approach] Using Memoization- O(n2) time and O(n2) space

The idea is that we want to prioritize using the paid painter for walls that are cheaper and takelonger to paint because this will help us to use the free painter to work for longer time. This looks like a greedy problem but formulating into strategy is difficult because each decision impacts subsequent choices. Determining which walls to pay for and which to allocate to the free painter becomes complex. We will use dynamic programming to explore all possible decisions.

Step-by-step approach:

  • Let dp(i, remain) represent the minimum cost to paint remain walls starting from index i. There are two base cases:
    • If remain <= 0: All walls are painted, return 0.
    • If i == n: This represents no more walls to assign, return a large value (infinity).
  • For the ith wall, we have two options. We can either hire the paid painter for this wall or not hire them.
    • If we hire painter for ith wall then cost would be cost[i] + dp(i + 1, remain - 1 - time[i])
    • If we don't hire for ith wall then cost would be dp(i + 1, remain) and we simply move to the next index.

Below is the implementation of the above approach


Output
Minimum cost: 3

Time Complexity: O(n^2), where n is the number of walls.
Auxiliary Space: O(n^2)


Comment
Article Tags: