Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find out the cells containing maximum value in a matrix in Python
Suppose, there is a n x n matrix initialized with 0s. Now, a list is given and it contains some pairs that contain a particular row and a column position. For each item i in the list, the contents of the cells increase by 1 where the row number and the column number are less than the row value and column value of item i in the list. After all the list elements have been traversed, we have to find out the number of cells in the matrix that contains the maximum value. (row and column index start at 0)
Problem Explanation
Let's understand this with an example. If the input is like input_list = [[3, 5], [4, 6], [5, 3]], then the output will be 9.
Suppose, it is a 5 x 6 matrix. At first the values in the matrix are ?
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
After the first element [3, 5] of the list have been traversed, it becomes ?
1 1 1 1 1 0 1 1 1 1 1 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0
After the second element [4, 6] of the list have been traversed, it becomes ?
2 2 2 2 2 1 2 2 2 2 2 1 2 2 2 2 2 1 1 1 1 1 1 1 0 0 0 0 0 0
After the third element [5, 3] has been traversed, it becomes ?
3 3 3 2 2 1 3 3 3 2 2 1 3 3 3 2 2 1 2 2 2 1 1 1 1 1 1 0 0 0
The maximum value in the matrix is 3, and there are 9 cells that contain the value.
Solution Approach
To solve this, we will follow these steps ?
- xpos := 0
- ypos := 0
- for each item in input_list, do
- if xpos is same as 0, then
- xpos := item[0]
- ypos := item[1]
- otherwise,
- xpos := minimum of (xpos, item[0])
- ypos := minimum of (ypos, item[1])
- if xpos is same as 0, then
- return(xpos * ypos)
Example
Let us see the following implementation to get better understanding ?
def solve(input_list):
xpos = 0
ypos = 0
for item in input_list:
if xpos == 0:
xpos = item[0]
ypos = item[1]
else:
xpos = min(xpos, item[0])
ypos = min(ypos, item[1])
return (xpos * ypos)
print(solve([[3, 5], [4, 6], [5, 3]]))
The output of the above code is ?
9
How It Works
The key insight is that the maximum value in the matrix will be at the intersection of the minimum row and minimum column values from all pairs. This is because:
- Each pair
[r, c]increments all cells where row < r and column < c - The cells that get incremented by all pairs are those with coordinates less than the minimum row and minimum column values
- The number of such cells is
min_row * min_column
Conclusion
This problem demonstrates how to efficiently find maximum value cells in a matrix by identifying the overlap region that gets incremented by all operations. The solution runs in O(n) time where n is the number of pairs.
