Paint House II

There is a row of n houses, where each house can be painted with one of k colors. The cost of painting each house with a certain color is represented by an n x k cost matrix costs.

Return the minimum cost to paint all houses such that no two adjacent houses have the same color.

  • If n == 0, return 0.
  • If k == 0, return 0.
  • If n == 1, return the minimum value in costs[0] (equivalently the sole cost when k == 1).
  • If n > 1 and k == 1, it is impossible to paint every pair of adjacent houses with different colors. In that case, return -1.

The challenge is to solve this in O(n*k) time with O(1) extra space beyond the input.

Examples
Input: [[1,5,3],[2,9,4]]
Output: 5
Hints

Paint House II

There is a row of `n` houses, where each house can be painted with one of `k` colors. The cost of painting each house with a certain color is represented by an `n x k` cost matrix `costs`.