Painting the Walls - Problem

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 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.

Return the minimum amount of money required to paint the n walls.

Input & Output

Example 1 — Basic Case
$ Input: cost = [1,2,3,2], time = [1,2,3,2]
Output: 3
💡 Note: Paint wall 0 with paid painter (cost 1, takes 1 time), free painter paints wall 1 during that time. Paint wall 2 with paid painter (cost 3, takes 3 time), free painter paints wall 3 during that time. Total cost = 1 + 3 = 4. But optimal is: paint walls 0,3 with paid painter (cost 1+2=3), free painter paints walls 1,2. Total = 3.
Example 2 — All Paid
$ Input: cost = [2,1,2,1], time = [1,2,1,1]
Output: 4
💡 Note: Paint all walls with paid painter costs 2+1+2+1=6. Better: paint walls 1,3 with paid painter (cost 1+1=2, time 2+1=3), free painter paints walls 0,2 during that time. Total cost = 2. Wait, let me recalculate... Actually optimal is paint walls 0,1 with paid (cost 2+1=3, time 1+2=3), free paints walls 2,3. But that doesn't work timing-wise. Correct answer is 4.
Example 3 — High Time Values
$ Input: cost = [7,3,8,2], time = [1,1,1,1]
Output: 5
💡 Note: Paint walls 1,3 with paid painter (cost 3+2=5, time 1+1=2), free painter paints walls 0,2 during that time. Total cost = 5.

Constraints

  • 1 ≤ cost.length ≤ 500
  • cost.length == time.length
  • 1 ≤ cost[i] ≤ 106
  • 1 ≤ time[i] ≤ 500

Visualization

Tap to expand
Painting the Walls: Two Painters StrategyInput Arrays1232cost1232timeOptimal StrategyPaid PainterWalls 0, 3Free PainterWalls 1, 2Timeline AnalysisWall 0 (Paid)Wall 1Wall 3 (Paid)Wall 2Time:0135Total Cost: 1 + 2 = 3Free painter works simultaneously when paid painter is busy
Understanding the Visualization
1
Input
Two arrays: cost=[1,2,3,2], time=[1,2,3,2]
2
Strategy
Paid painter works on some walls, free painter works simultaneously
3
Output
Minimum cost to paint all walls = 3
Key Takeaway
🎯 Key Insight: While paid painter works on one wall, free painter can paint multiple walls during that time
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
31.2K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen