Here's a simple question from leetcode, https://leetcode.com/problems/paint-house/description/
There are a row of n houses, each house can be painted with one of the three colors: red, blue or green. 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 a n x 3 cost matrix. For example, costs[0][0] is the cost of painting house 0 with color red; costs[1][2] is the cost of painting house 1 with color green, and so on... Find the minimum cost to paint all houses.
Based on my understanding of the problem, here's my solution, which is verbose, but intentionally so,
import sys
class Solution(object):
def minCost(self, costs):
"""
:type costs: List[List[int]]
:rtype: int
"""
if costs is None or len(costs) == 0:
return 0
memo = [0 for _ in range(len(costs))]
house, cost = self.get_min_cost_and_index(costs[0])
memo[0] = cost
for i in range(1, len(costs)):
curr_house, curr_cost = self.get_min_cost_and_index(costs[i])
if curr_house == house:
mod_house, mod_cost = self.get_min_cost_and_index_minus_one(costs[i], house)
memo[i] = memo[i-1] + mod_cost
house = mod_house
else:
memo[i] = memo[i-1] + curr_cost
house = curr_house
return memo[-1]
def get_min_cost_and_index(self, row):
min_val, index = sys.maxsize, -1
for i,v in enumerate(row):
if v < min_val:
min_val = v
index = i
return index, min_val
def get_min_cost_and_index_minus_one(self, row, minus):
min_val, index = sys.maxsize, -1
for i, v in enumerate(row):
if i == minus:
continue
if v < min_val:
min_val = v
index = i
return index, min_val
The problem is on the test case below it fails,
if __name__ == '__main__':
solution = Solution()
print(solution.minCost([[5,8,6],[19,14,13],[7,5,12],[14,15,17],[3,20,10]]))
My solution gives 47
which is correct as per the logic I've implemented. The correct answer though is 43
and I can't how and why
Can someone help me what I'm missing out?