You are given a 2D matrix ‘ARR’ of size ‘N x 3’ having integers, where ‘N’ is the number of rows.
Your task is to find the smallest sum possible while taking one element from each row.
The rules for selecting elements are as follows-
1. In a row, after selecting an element at a given position, you cannot select the element directly below it
2. You can only select elements that are not directly below the previously selected element.
The first line contains a single integer ‘T’ denoting the number of test cases.
The first line of every test case contains a single integer, ‘N’ denoting the number of rows.
Then each of the ‘N’ rows contains three elements.
Output format:
For each test case, return the smallest sum possible as per the rules.
Output for each test case is printed on a separate line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^3
0 <= ARR[i][j] <= 10^3
Where ‘ARR[i][j]’ denotes the matrix element at the jth column in the ith row
Time Limit: 1 sec
2
2
1 2 3
4 5 6
1
3 5 6
6
3
For the first test case,
There are only six possible sums as per rules:
(i) 1 -> 5 with sum equal to 6.
(ii) 1 -> 6 with sum equal to 7.
(iii) 2 -> 4 with sum equal to 6.
(iv) 2 -> 8 with sum equal to 8.
(v) 3 -> 4 with sum equal to 7.
(vi) 3 -> 5 with sum equal to 8.
So the minimum among all of these is 6. So the output is 6.
For the second test case,
Since the given matrix has a single row so the possible sum can be {3, 5, 6} and the minimum among all of them is 3. So the output is 3.
2
2
4 5 6
7 8 9
2
4 8 9
6 10 12
12
14
For the first test case,
There are only six possible sums as per rules:
(i) 4 -> 8 with sum equal to 12 .
(ii) 4 -> 9 with sum equal to 13.
(iii) 5 -> 7 with sum equal to 12.
(iv) 5 -> 9 with sum equal to 14.
(v) 6 -> 7 with sum equal to 13.
(vi) 6 -> 8 with sum equal to 14.
So the minimum among all of these is 12. So the output is 12.
For the second test case,
There are only six possible sums as per rules:
(i) 4 -> 10 with sum equal to 14.
(ii) 4 -> 12 with sum equal to 16.
(iii) 8 -> 6 with sum equal to 14.
(iv) 8 -> 12 with sum equal to 20.
(v) 9 -> 6 with sum equal to 15.
(vi) 9 -> 10 with sum equal to 19.
So the minimum among all of these is 14. So the output is 14.
Recursively find all the combinations.
O(2^N), where ‘N’ is the number of rows.
We are using the recursion for forming all possible combinations. As in each function call, we have 2 options available. Hence, the time complexity will be O(2^N). So the overall time complexity will be O(2^N).
O(1).
Since we are using a recursive function and in the worst case, there can be O(Z) states where Z = 3 in the recursion stack which does not have much effect on the overall space complexity. Therefore, constant space is being used. So, the overall space complexity will be O(1).