Paint House

You have been given ‘N’ houses, each house can be painted with any of three colours: green, red and yellow. You are also given a “cost” matrix of ‘N’ * 3 dimension which represents the cost of painting an i-th house (0-th based indexing) with j-th colour. The colour code is as follows: green - 0, red - 1 and yellow - 2. Now, you are supposed to find the minimum cost of painting all houses such that no adjacent houses are painted with the same colour.

Input Format :
The first line contains an integer ‘T’ denoting the number of test cases. Then each test case follows.

The first input line of each test case contains an integer ‘N’ denoting the number of houses.

Each of the next ‘N’ lines contains 3 space-separated integers denoting the cost of painting the i-th house with the green,red and yellow color respectively.  
Output Format :
For each test case, print the minimum cost of painting all houses such that no adjacent houses are painted with the same colour.

Print the output of each test case in a separate line.
Note :
You are not required to print the expected output; it has already been taken care of. Just implement the function.
Constraints :
1 <= T <= 50
1 <= N <= 10000
0 <= cost[i][j] <= 100

Where cost[i][j] represents the cost of painting the i-th house with j-th colour.

Time limit: 1 sec
CodingNinjas
author
2y
Recursive Approach

The basic idea of this approach is to break the original problem into sub-problems. We will try to check each valid way of painting the houses. And, then find the minimum cost.

Now,...read more

CodingNinjas
author
2y
Memoization

Let us observe the recursion tree for the first test case of sample test 2.


After observing the tree, we’ll find that there are some redundant function calls which means that there are som...read more

CodingNinjas
author
2y
Dynamic Programming

The basic idea of this approach is to solve the problem iteratively.


Let dp[ i ][ j ] be our dynamic programming matrix of N * 3 dimensions to store the minimum cost to paint first ...read more

CodingNinjas
author
2y
Dynamic Programming - Space Optimized

We can observe in approach 3 that the current state depends on one immediate previous house. This suggests we can use three variables to store the cost of painting...read more

Add answer anonymously...
Springworks Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter