37
loading...
This website collects cookies to deliver better user experience
k
is always 3. If we solve the second problem, then we can also solve the first problem. Therefore, let's think about the case when k
is not fixed. def minCostII(self, costs: List[List[int]]) -> int:
n = len(costs)
k = len(costs[0])
prev_row = costs[0]
for house in range(1, n):
cur_row = [0] * k
for cur_color in range(k):
prev_best = math.inf
for prev_color in range(k):
if cur_color == prev_color:
continue
prev_best = min(prev_best, prev_row[prev_color])
cur_row[cur_color] += prev_best + costs[house][cur_color]
prev_row = cur_row
return min(prev_row)
def minCostII(self, costs: List[List[int]]) -> int:
k = len(costs[0])
prev_row = [0] * k
for cur_row in costs:
prev_row = [cur_row[i] + min(prev_row[:i] + prev_row[i + 1:]) for i in range(k)]
return min(prev_row)
n
and k
are set to $500$, then Solution 1 will exceed time limit. Here's another solution using the idea of Markov Chain. Given that k
states (colors) and n
stages, we can update the matrix to find out the optimal value for each state at the current stage. The idea is to find out the first and the second minimum cost for each stage. For the next stage, we can update each cost by adding either the first minimum cost or the second one. The reason we need two minimum cost is that we cannot paint the same color. If the index of the first minimum cost from the previous stage is i
and we have to use the second minimum cost for the current stage, and vice versa.class Solution:
def solve(self, matrix):
n = len(matrix)
k = len(matrix[0])
for house in range(1, n):
first_mi_color = second_mi_color = None
# find first & second min color
for color in range(k):
cost = matrix[house - 1][color]
if first_mi_color is None or cost < matrix[house - 1][first_mi_color]:
second_mi_color = first_mi_color
first_mi_color = color
elif second_mi_color is None or cost < matrix[house - 1][second_mi_color]:
second_mi_color = color
# update matrix for the current row
for color in range(k):
if color == first_mi_color:
matrix[house][color] += matrix[house - 1][second_mi_color]
else:
matrix[house][color] += matrix[house - 1][first_mi_color]
return min(matrix[-1])
class Solution:
def minCostII(self, costs: List[List[int]]) -> int:
n, k = len(costs), len(costs[0])
for house in range(1, n):
first_mi_cost = min(costs[house - 1])
idx = costs[house - 1].index(first_mi_cost)
second_mi_cost = min(costs[house - 1][:idx] + costs[house - 1][idx + 1:])
for color in range(k):
if color == idx:
costs[house][color] += second_mi_cost
else:
costs[house][color] += first_mi_cost
return min(costs[-1])