#2742
Painting the Walls
HardArrayDynamic ProgrammingDynamic ProgrammingGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n²)Space O(n)
The optimal solution uses dynamic programming to keep track of the minimum cost required to paint the walls while considering the constraints of the two painters. This approach is efficient and avoids redundant calculations.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a DP array where dp[i] represents the minimum cost to paint the first i walls.
- 2Step 2: Iterate through each wall and for each wall, decide whether to use the paid painter or the free painter based on the time taken.
- 3Step 3: Update the DP array by considering the cost of using the paid painter for the current wall and the time taken for the previous walls.
- 4Step 4: Return the value in dp[n] which represents the minimum cost to paint all walls.
solution.py11 lines
1# Full working Python code
2
3def min_cost(cost, time):
4 n = len(cost)
5 dp = [float('inf')] * (n + 1)
6 dp[0] = 0
7 for i in range(1, n + 1):
8 for j in range(i):
9 dp[i] = min(dp[i], dp[j] + cost[j] + (i - j - 1))
10 return dp[n]
11ℹ
Complexity note: The complexity is O(n²) because we are using a nested loop to fill the DP array, where n is the number of walls.
- 1The free painter can only be used when the paid painter is busy, which creates a dependency on the order of painting.
- 2Dynamic programming helps in breaking down the problem into smaller subproblems, allowing us to build the solution incrementally.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.