VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimize-the-absolute-difference-on-path-from-first-column-to-the-last-column/

⇱ Minimize the absolute difference on path from first column to the last column - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimize the absolute difference on path from first column to the last column

Last Updated : 29 Feb, 2024

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:

  • Sorting:
    • The function starts by creating list res containing tuples of values from the matrix along with their corresponding column indices. This list is then sorted based on the values.
  • Sliding Window Technique:
    • A deque (dq) is used to implement a sliding window over the sorted list of tuples.
    • A defaultdict (hsh) is used to keep track of the columns included in the current window.
    • Two pointers, i and j, are used to define the current window. Initially, i is set to 0, and j iterates through the sorted list.
  • Minimize Window:
    • The window expands to the right (j) by incrementing the frequency of the current column in the hsh dictionary.
    • The window contracts from the left (i) when the length of hsh reaches M. The frequency of the leftmost column is decreased, and if it becomes zero, the column is removed from hsh.
  • Update Minimum Cost:
    • While maintaining the window, the difference between the maximum and minimum values within the window is computed (res[j][0] - res[i][0]).
    • The minimum cost is updated whenever a smaller difference is found.
  • Final Result:
    • The final result is the minimum cost obtained during the entire process.

Below is the Implementation of the algorithm:


Output
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)

Comment