Maximum Difference Solution || Difference Between Largest Number and Smallest Number Solution

 Maximum Difference Solution:

Given a matrix of size N * M where N represent number of rows and M represents number of columns.

For a row we define a value called DiffValue which is difference between its largest term and the smallest term i.e (maximum term - minimum term). You have to answer the largest DiffValue among all the rows for the given matrix.

Input

  • First line  contains two space separated integers N and M
  • Next N lines contain space separated integers each denoting a row of the given matrix.

Output

Output a single line containing the maximum difference value of the given matrix.

Constraints

  • 1 ≤ T ≤ 25
  • 1 ≤ N,M ≤ 500
  • 1 ≤ Value ≤ 10000

Sample Input:

2 3

5 1 3

2 10 6

Sample Output

8

Explanation:

Difference value for row 1 is 4. Difference value of row 2 is 8.  Hence, Maximum difference value over both the rows is 8

 
SAMPLE INPUT
 
2 3
5 1 3
2 10 6
SAMPLE OUTPUT
 
8







*(Note do the program in Python 3)

Program:


n, m = map(int, input().split())
matrix = []

for i in range(n):
row = list(map(int, input().split()))
matrix.append(row)

max_diff = 0

for i in range(n):
min_val = matrix[i][0]
max_val = matrix[i][0]
for j in range(1, m):
if matrix[i][j] < min_val:
min_val = matrix[i][j]
if matrix[i][j] > max_val:
max_val = matrix[i][j]
diff = max_val - min_val
if diff > max_diff:
max_diff = diff

print(max_diff)


Explanation:

        This code reads in a matrix of integers with dimensions n x m, where n and m are determined by the user input. The code then calculates the maximum difference between the minimum and maximum values in each row of the matrix, and outputs the maximum difference found.

        The input is read using a for loop that runs n times, with each iteration reading a row of integers from the input and appending it to the matrix list.

        The maximum difference is calculated using another for loop that iterates over each row of the matrix. For each row, the minimum and maximum values are initially set to the first value in that row. The loop then iterates over the remaining values in the row and updates the minimum and maximum values as necessary. Finally, the difference between the maximum and minimum values is calculated, and if this difference is greater than the current maximum difference found so far, it is updated.

        The code outputs the maximum difference found at the end.

Note: the code assumes that the input is valid and no error checking is performed. It also assumes that the input values are separated by whitespace.

Post a Comment

0 Comments