Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Dynamic Programming

Paint House

Medium · Dynamic Programming · Asked at LinkedIn, Amazon, Google

A row of n houses must each be painted red, blue or green, and no two neighbouring houses may have the same colour. cost[i][c] is the price of painting house i with colour c. Print the minimum total cost.

Input

First line: n. Next n lines: three costs (red, blue, green).

Output

The minimum total cost.

Constraints

dp[c] = cheapest way to paint houses so far with the last one coloured c. For the next house: new[c] = cost[c] + min(dp of the two other colours). Only three numbers are kept.

Example 1

Input

3
17 2 17
16 16 5
14 3 19

Output

10

Example 2

Input

1
7 6 2

Output

2

Hints

  1. Only the colour of the previous house matters for the next choice.
  2. Keep the cheapest total for each possible colour of the last house.
  3. Colour c for the next house can follow either of the two other colours.

Approach

Let (r, b, g) be the minimum costs so far with the last house painted red, blue or green. For the next house with costs (cr, cb, cg): newR = cr + min(b, g), newB = cb + min(r, g), newG = cg + min(r, b). After all houses, the answer is min(r, b, g). Only three numbers are stored.

Complexity: O(n) time · O(1) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    long long r = 0, b = 0, g = 0;
    for (int i = 0; i < n; i++) {
        long long cr, cb, cg;
        cin >> cr >> cb >> cg;
        long long nr = cr + min(b, g), nb = cb + min(r, g), ng = cg + min(r, b);
        r = nr;
        b = nb;
        g = ng;
    }
    cout << min({r, b, g}) << "\n";
    return 0;
}

Python solution

import sys

data = list(map(int, sys.stdin.read().split()))
n = data[0]
r = b = g = 0
for i in range(n):
    cr, cb, cg = data[1 + 3 * i], data[2 + 3 * i], data[3 + 3 * i]
    r, b, g = cr + min(b, g), cb + min(r, g), cg + min(r, b)
print(min(r, b, g))

Java solution

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int n = (int) in.nval;
        long r = 0, b = 0, g = 0;
        for (int i = 0; i < n; i++) {
            in.nextToken();
            long cr = (long) in.nval;
            in.nextToken();
            long cb = (long) in.nval;
            in.nextToken();
            long cg = (long) in.nval;
            long nr = cr + Math.min(b, g), nb = cb + Math.min(r, g), ng = cg + Math.min(r, b);
            r = nr;
            b = nb;
            g = ng;
        }
        System.out.println(Math.min(r, Math.min(b, g)));
    }
}

Solve Paint House online · All practice problems