265. Paint House II (Hard) - TengnanYao/daily_leetcode GitHub Wiki

class Solution(object):
    def minCostII(self, costs):
        """
        :type costs: List[List[int]]
        :rtype: int
        """
        n, k = len(costs), len(costs[0])
        if n == 1:
            return min(costs[-1])
        arr = sorted([x, i] for i, x in enumerate(costs[0]))
        a, b = arr[0][1], arr[1][1]
        for i in range(1, n):
            for j in range(k):
                costs[i][j] += costs[i - 1][b] if j == a else costs[i - 1][a]
            arr = sorted([x, j] for j, x in enumerate(costs[i]))
            a, b = arr[0][1], arr[1][1]
        return min(costs[-1])