Paint House – Python 3 (Week 17 – 12)

class Solution:
    """
    @param costs: n x 3 cost matrix
    @return: An integer, the minimum cost to paint all houses
    """
    def minCost(self, cost):
        # write your code here
        if len(cost) == 0:
            return 0
            
        for i in range(1, len(cost)):
            for j in range(3):
                cost[i][j] = cost[i][j] + min(cost[i - 1][(j + 1) % 3], cost[i - 1][(j + 2) % 3])
        
        return min(cost[-1][0], cost[-1][1], cost[-1][2])

Time O(n). Space O(1).

Leave a comment

Design a site like this with WordPress.com
Get started