Advertisement
Iam_Sandeep

Find a specific pair in Matrix maximum value of mat(c, d) – mat(a, b) over all choices of indexes s

Aug 1st, 2022
1,264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.78 KB | None | 0 0
  1. '''
  2. Given an n x n matrix mat[n][n] of integers, find the maximum value of mat(c, d) – mat(a, b) over all choices of indexes such that both c > a and d > b
  3. '''
  4.  
  5. def findMaxValue(mat, n):
  6.     dp=[[float('inf')]*n for i in range(n)]
  7.     dp[0][0]=mat[0][0]#This is min for matrix 0,0 to (1,1)
  8.     ans=float('-inf')
  9.     #dp[i][j] stores minimum from 0,0 to i-1,j-1 rectangle
  10.  
  11.     for i in range(n):
  12.         for j in range(n):
  13.             if i>=1:
  14.                 dp[i][j]=min(dp[i][j],dp[i-1][j],mat[i][j])
  15.             if j>=1:
  16.                 dp[i][j]=min(dp[i][j],dp[i][j-1],mat[i][j])
  17.             if i>=1 and j>=1:
  18.                 ans=max(ans,mat[i][j]-dp[i-1][j-1])#minimum of (i-1,j-1)'s rectangle at dp[i][j] i.e. 0,0 to (i-1,j-1) is stored at dp[i][j]
  19.     return ans
  20.    
  21.    
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement