Problem description:

There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.

The cost of painting each house with a certain color is represented by an n x k cost matrix costs.

  • For example, costs[0][0] is the cost of painting house 0 with color 0; costs[1][2] is the cost of painting house 1 with color 2, and so on…

Return the minimum cost to paint all houses.

Example 1:

1
2
3
4
5
Input: costs = [[1,5,3],[2,9,4]]
Output: 5
Explanation:
Paint house 0 into color 0, paint house 1 into color 2. Minimum cost: 1 + 4 = 5;
Or paint house 0 into color 2, paint house 1 into color 0. Minimum cost: 3 + 2 = 5.

Example 2:

1
2
Input: costs = [[1,3],[2,4]]
Output: 5

Constraints:

  • costs.length == n
  • costs[i].length == k
  • 1 <= n <= 100
  • 1 <= k <= 20
  • 1 <= costs[i][j] <= 20

Solution:

Update the whole array. Find two smallest elements, min1 min2, in previous row costs[i-1].

Then when we update every column in row cost[i-1].

If index is the same as previous row’s smallest element, then we use min2 instead.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution:
def minCostII(self, costs: List[List[int]]) -> int:
# find first two smallest elements, min1 min2, in previous row
# if current row's smallest color is the same as previous row, then we use min2 in previous row
# else we directly
if not costs: return 0
n, k = len(costs), len(costs[0])
for i in range(1, n):
min1 = min(costs[i-1])
idx = costs[i-1].index(min1)
min2 = min(costs[i-1][:idx]+costs[i-1][idx+1:])

for j in range(k):
if j != idx:
costs[i][j] += min1
else:
costs[i][j] += min2
return min(costs[-1])

time complexity: $O(nk)$
space complexity: $O(1)$
reference:
related problem: