

If the given ‘HOUSES’ array is [0,2,1,2,0] and ‘COST’ array is [ [1,7],[1,1],[1,1],[1,1], [5,1] ] and ‘M’ = 3.
The minimum cost will be 7+1 =8. We will colour the first house with colour 2 and the last house with colour 1.
The first line of the input contains an integer, 'T,’ denoting the number of test cases.
The first line of each test case contains three integers, 'N’,’K’, and ‘M’, denoting the number of houses, the number of colours available, and the number of neighbourhood groups, respectively.
The next line of each test case has ‘HOUSES’ array.
The next ‘N’ lines of each test case have ‘K’ values corresponding to the values of ‘COST[i]’ for all ‘K’ colours.
For each test case, return an integer corresponding to the minimum cost possible or -1.
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 100.
1 <= K <= 10
1 <= M <= N
0 <= COST[i][j] <= 1000
Time limit: 1 sec
In this approach, we will use a recursive function to find the minimum cost required. We will define a function HELPER(‘IDX’,’ TARGET’,’LAST_COLOR’,’ HOUSES’,’ COST’).IDX is the current index of ‘HOUSE,’ and ‘TARGET’ is the remaining number of neighborhood groups and ‘LAST_COLOR’ is the color of the last house. We will try each color for the houses which are not painted yet (‘HOUSES’[IDX] == 0).
In the previous approach, we used a recursive function to find the answer.
In this approach, we will use dynamic programming to formulate the answer. We will use the same function 'HELPER'(), but we will also use memoization and store the values in the ‘DP’ table to use the precomputed values.
In this approach, we will build up a ‘DP’ table of size ‘DP’[‘N’+1][‘K’+1][‘M’+1].DP[i][j][k] will denote the minimum cost for the first i houses, and i’th house is painted with j’th color, and there are k neighborhood groups. We will iterate over all the ‘DP’ states and find their value using the following conditions:
2. If ‘HOUSES[i]’ is 0, we will try all colors for this building and pick the color which gives the total minimum cost.
At last, we will iterate over all color k and find the minimum among DP[‘N’-1][k][‘M’] for all ‘k’.