![]() |
VOOZH | about |
Given an integer matrix mat[][] with N rows and M columns. The task is to minimize the absolute difference between the maximum and minimum elements visited along the path from the first column to the last column. We can jump from the current column to any row in the next column.
Note: We can start from first column (any row) and end at last column (any row).
Examples:
Input: N = 3, M = 3, mat[][] = {{1, 2, 3}, {1, 2, 3}, {2, 1, 1}}
Output: 0
Explanation: We travel along the path A[0][0], A[2][1], A[2][2]. Cost of the path is 1 - 1 = 0.Input: N = 1, M = 4, mat[][] = {{1, 2, 3, 4}}
Output: 3
Explanation: There is only one path A[0][0], A[0][1], A[0][2], A[0][3]. Cost of the path is 4 - 1 = 3.
Approach: To solve the problem, follow the below idea:
The approach is to first store the elements in vector along with column index. After sorting the vector, iterate here and if all indexes are being stored in map it means we have iterated through all the columns. Get the minimum and maximum element and get the difference and update the minimum value.
Step-by-step algorithm:
Below is the Implementation of the algorithm:
0
Time Complexity: O(N * M * log(N * M)), where N is the number of rows and M is the number of columns.
Auxiliary Space: O(M)