Coding Problem 10
Minimum Cost Required
asked by Facebook
Ques. A builder is looking to build a row of N houses that can be of K different colors. He has a goal of minimizing cost while ensuring that no two neighbouring houses are of same color. Given an N by K matrix where the nth row and kth column represents the cost to build the nth house with kth color return the minimum cost which achieves this goal.
Solution.
Suppose we have cost matrix like this -
[ [2, 1, 1],
[1, 10, 3],
[1, 2, 100] ]
Each row represents the house and each column represents the color so the values are the cost of painting the color for a house.
Since we know that indexes starts from 0 so cost of painting house number 0 with color number 0 id 2. Cost of painting house number 1 with color number 2 is 3.
Our task is to minimize the cost without repeating the color in adjacent house. For example if we use color number 0 in house number 0 then we can not use that color in next house means house number 1 but we can use that in house number 2. So how can we minimize the cost?
Well my idea is to keep a temporary array in which we store the total cost upto the traversed matrix. Initially we will keep the first row in the temporary list and then for next row we will add the minimum value from next row the the current temporary variable but the condition is that for each index in temporary variable we will not add that same index value of the next row because we know that no two adjacent house will be of same color.
As you can see in the image that final result will be 4 which is the minimum cost possible so that no two adjacent houses will be of same color. Lets code this method -
def solution(costs):
best = [0]*len(costs[0])
for cost in costs:
temp = [0]*len(costs[0])
for index in range(len(cost)):
temp[index]= cost[index]+min(best[:index]+best[index+1:])
best=temp
return min(best)
costs = [[2, 1, 1],
[1, 10, 3],
[1, 2, 100]]
print("Lowest cost possible is: {0} ".format(solution(costs)))
Output: Lowest cost possible is: 4

Comments
Post a Comment