#3429
Paint House IV
MediumArrayDynamic ProgrammingDynamic ProgrammingArray
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 build up the minimum cost while ensuring the constraints are met. This approach is efficient as it avoids redundant calculations.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a DP table to store the minimum costs for each house and color.
- 2Step 2: For each house, calculate the minimum cost for each color considering the previous house's colors and the equidistant constraints.
- 3Step 3: Return the minimum value from the last house's costs.
solution.py9 lines
1# Full working Python code
2def minCost(n, cost):
3 dp = [[0]*3 for _ in range(n)]
4 for j in range(3):
5 dp[0][j] = cost[0][j]
6 for i in range(1, n):
7 for j in range(3):
8 dp[i][j] = cost[i][j] + min(dp[i-1][(j+1)%3], dp[i-1][(j+2)%3])
9 return min(dp[n-1])ℹ
Complexity note: The time complexity is O(n) because we iterate through each house once, and for each house, we perform a constant amount of work (calculating the minimum cost for 3 colors).
- 1The adjacency constraint requires careful consideration of the previous house's color.
- 2The equidistant constraint can be managed by ensuring that colors at mirrored positions are different.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.