Suppose we have a matrix, we have to find the total number of integers whose value is the largest in its row and column.
So, if the input is like
1 | 3 | 2 |
4 | 6 | 5 |
1 | 5 | 7 |
then the output will be 2 as 6 and 7 are valid.
To solve this, we will follow these steps −
mat := matrix
r_maxes := make a list of max elements of each row of mat
c_maxes := make a list of max elements of each column of mat
a := a new list
for r in range 0 to number of rows - 1, do
for c in range 0 to number of columns - 1, do
v := mat[r, c]
if r_maxes[r] is v and c_maxes[c] is v, then
insert v at the end of a
return size of a
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, matrix): mat = matrix trans_mat = list(zip(*matrix)) print(mat, trans_mat) r_maxes = [max(row) for row in mat] c_maxes = [max(t_row) for t_row in trans_mat] a = [] for r in range(len(mat)): for c in range(len(trans_mat)): v = mat[r][c] if (r_maxes[r], c_maxes[c]) == (v, v): a.append(v) return len(a) ob = Solution() matrix = [ [1, 3, 2], [4, 6, 5], [1, 5, 7] ] print(ob.solve(matrix))
Input
[[1, 3, 2], [4, 6, 5], [1, 5, 7]]
Output
2