Maximum and Minimum in a square matrix.
Last Updated :
13 Sep, 2023
Given a square matrix of order n*n, find the maximum and minimum from the matrix given.
Examples:
Input : arr[][] = {5, 4, 9,
2, 0, 6,
3, 1, 8};
Output : Maximum = 9, Minimum = 0
Input : arr[][] = {-5, 3,
2, 4};
Output : Maximum = 4, Minimum = -5
Naive Method :
We find maximum and minimum of matrix separately using linear search. Number of comparison needed is n2 for finding minimum and n2 for finding the maximum element. The total comparison is equal to 2n2.
C++
// C++ program for finding maximum and minimum in
// a matrix.
#include<bits/stdc++.h>
using namespace std;
// Finds maximum and minimum in arr[0..n-1][0..n-1]
// using pair wise comparisons
void maxMin(int arr[3][3], int n)
{
int min = INT_MAX;
int max = INT_MIN;
// for finding the max element in given array
for(int i = 0; i<n; i++){
for(int j = 0; j<n; j++){
if(max < arr[i][j]) max = arr[i][j];
}
}
// for finding the min element in given array
for(int i = 0; i<n; i++){
for(int j = 0; j<n; j++){
if(min > arr[i][j]) min = arr[i][j];
}
}
cout << "Maximum = " << max << ", Minimum = " << min;
}
// Driver Program to test above function
int main(){
int arr[3][3] = {{5, 9, 11} , {25, 0, 14} , {21, 6, 4}};
maxMin(arr, 3);
return 0;
}
// THIS CODE IS CONTRIBUTED BY Yash Agarwal(yashagarwal23121999)
Java
import java.util.*;
class Main {
// Finds maximum and minimum in arr[0..n-1][0..n-1]
// using pair wise comparisons
static void maxMin(int[][] arr, int n) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
// for finding the max element in given array
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(max < arr[i][j]) max = arr[i][j];
}
}
// for finding the min element in given array
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(min > arr[i][j]) min = arr[i][j];
}
}
System.out.println("Maximum = " + max + ", Minimum = " + min);
}
public static void main(String[] args) {
int[][] arr = {{5, 9, 11}, {25, 0, 14}, {21, 6, 4}};
maxMin(arr, 3);
}
}
Python3
import sys
# Finds maximum and minimum in arr[0..n-1][0..n-1]
# using pair wise comparisons
def maxMin(arr, n):
min = sys.maxsize
max = -sys.maxsize - 1
# for finding the max element in given array
for i in range(n):
for j in range(n):
if max < arr[i][j]:
max = arr[i][j]
# for finding the min element in given array
for i in range(n):
for j in range(n):
if min > arr[i][j]:
min = arr[i][j]
print("Maximum = ", max, ", Minimum = ", min)
# Driver Program to test above function
arr = [[5, 9, 11], [25, 0, 14], [21, 6, 4]]
maxMin(arr, 3)
C#
// C# program for finding maximum and minimum in
// a matrix.
using System;
class Program
{
// Finds maximum and minimum in arr[0..n-1][0..n-1]
// using pair wise comparisons
static void MaxMin(int[,] arr, int n)
{
int min = int.MaxValue;
int max = int.MinValue;
// for finding the max element in given array
for(int i = 0; i<n; i++){
for(int j = 0; j<n; j++){
if(max < arr[i, j]) max = arr[i, j];
}
}
// for finding the min element in given array
for(int i = 0; i<n; i++){
for(int j = 0; j<n; j++){
if(min > arr[i, j]) min = arr[i, j];
}
}
Console.WriteLine("Maximum = {0}, Minimum = {1}", max, min);
}
// Driver Program to test above function
static void Main(string[] args)
{
int[,] arr = {{5, 9, 11} , {25, 0, 14} , {21, 6, 4}};
MaxMin(arr, 3);
}
}
JavaScript
// JavaScript program for finding maximum and minimum in
// a matrix
// Finds maximum and minimum in arr[0..n-1][0..n-1]
// using pair wise comparisons
function maxMin(arr, n){
let min = +2147483647;
let max = -2147483648;
// for finding the max element in givne array
for(let i = 0; i<n; i++){
for(let j = 0; j<n; j++){
if(max < arr[i][j]) max = arr[i][j];
}
}
// for finding the min element in givne array
for(let i = 0; i<n; i++){
for(let j = 0; j<n; j++){
if(min > arr[i][j]) min = arr[i][j];
}
}
console.log("Maximum = " + max + ", Minimum = " + min);
}
// driver program to test above function
let arr = [[9,9,11], [25,0,14], [21,6,4]];
maxMin(arr, 3)
OutputMaximum = 25, Minimum = 0
Pair Comparison (Efficient method):
Select two elements from the matrix one from the start of a row of the matrix another from the end of the same row of the matrix, compare them and next compare smaller of them to the minimum of the matrix and larger of them to the maximum of the matrix. We can see that for two elements we need 3 compare so for traversing whole of the matrix we need total of 3/2 n2 comparisons.
Note : This is extended form of method 3 of Maximum Minimum of Array.
Implementation:
C++
// C++ program for finding maximum and minimum in
// a matrix.
#include<bits/stdc++.h>
using namespace std;
#define MAX 100
// Finds maximum and minimum in arr[0..n-1][0..n-1]
// using pair wise comparisons
void maxMin(int arr[][MAX], int n)
{
int min = INT_MAX;
int max = INT_MIN;
// Traverses rows one by one
for (int i = 0; i < n; i++)
{
for (int j = 0; j <= n/2; j++)
{
// Compare elements from beginning
// and end of current row
if (arr[i][j] > arr[i][n-j-1])
{
if (min > arr[i][n-j-1])
min = arr[i][n-j-1];
if (max< arr[i][j])
max = arr[i][j];
}
else
{
if (min > arr[i][j])
min = arr[i][j];
if (max< arr[i][n-j-1])
max = arr[i][n-j-1];
}
}
}
cout << "Maximum = " << max
<< ", Minimum = " << min;
}
/* Driver program to test above function */
int main()
{
int arr[MAX][MAX] = {5, 9, 11,
25, 0, 14,
21, 6, 4};
maxMin(arr, 3);
return 0;
}
Java
// Java program for finding maximum
// and minimum in a matrix.
class GFG
{
static final int MAX = 100;
// Finds maximum and minimum
// in arr[0..n-1][0..n-1]
// using pair wise comparisons
static void maxMin(int arr[][], int n)
{
int min = +2147483647;
int max = -2147483648;
// Traverses rows one by one
for (int i = 0; i < n; i++)
{
for (int j = 0; j <= n/2; j++)
{
// Compare elements from beginning
// and end of current row
if (arr[i][j] > arr[i][n - j - 1])
{
if (min > arr[i][n - j - 1])
min = arr[i][n - j - 1];
if (max< arr[i][j])
max = arr[i][j];
}
else
{
if (min > arr[i][j])
min = arr[i][j];
if (max< arr[i][n - j - 1])
max = arr[i][n - j - 1];
}
}
}
System.out.print("Maximum = "+max+
", Minimum = "+min);
}
// Driver program
public static void main (String[] args)
{
int arr[][] = {{5, 9, 11},
{25, 0, 14},
{21, 6, 4}};
maxMin(arr, 3);
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python3 program for finding
# MAXimum and MINimum in a matrix.
MAX = 100
# Finds MAXimum and MINimum in arr[0..n-1][0..n-1]
# using pair wise comparisons
def MAXMIN(arr, n):
MIN = 10**9
MAX = -10**9
# Traverses rows one by one
for i in range(n):
for j in range(n // 2 + 1):
# Compare elements from beginning
# and end of current row
if (arr[i][j] > arr[i][n - j - 1]):
if (MIN > arr[i][n - j - 1]):
MIN = arr[i][n - j - 1]
if (MAX< arr[i][j]):
MAX = arr[i][j]
else:
if (MIN > arr[i][j]):
MIN = arr[i][j]
if (MAX< arr[i][n - j - 1]):
MAX = arr[i][n - j - 1]
print("MAXimum =", MAX, ", MINimum =", MIN)
# Driver Code
arr = [[5, 9, 11],
[25, 0, 14],
[21, 6, 4]]
MAXMIN(arr, 3)
# This code is contributed by Mohit Kumar
C#
// C# program for finding maximum
// and minimum in a matrix.
using System;
public class GFG {
// Finds maximum and minimum
// in arr[0..n-1][0..n-1]
// using pair wise comparisons
static void maxMin(int[,] arr, int n)
{
int min = +2147483647;
int max = -2147483648;
// Traverses rows one by one
for (int i = 0; i < n; i++)
{
for (int j = 0; j <= n/2; j++)
{
// Compare elements from beginning
// and end of current row
if (arr[i,j] > arr[i,n - j - 1])
{
if (min > arr[i,n - j - 1])
min = arr[i,n - j - 1];
if (max < arr[i,j])
max = arr[i,j];
}
else
{
if (min > arr[i,j])
min = arr[i,j];
if (max < arr[i,n - j - 1])
max = arr[i,n - j - 1];
}
}
}
Console.Write("Maximum = " + max +
", Minimum = " + min);
}
// Driver code
static public void Main ()
{
int[,] arr = { {5, 9, 11},
{25, 0, 14},
{21, 6, 4} };
maxMin(arr, 3);
}
}
// This code is contributed by Shrikant13.
PHP
<?php
// PHP program for finding
// maximum and minimum in
// a matrix.
$MAX = 100;
// Finds maximum and minimum
// in arr[0..n-1][0..n-1]
// using pair wise comparisons
function maxMin($arr, $n)
{
$min = PHP_INT_MAX;
$max = PHP_INT_MIN;
// Traverses rows one by one
for ($i = 0; $i < $n; $i++)
{
for ($j = 0; $j <= $n / 2; $j++)
{
// Compare elements from beginning
// and end of current row
if ($arr[$i][$j] > $arr[$i][$n - $j - 1])
{
if ($min > $arr[$i][$n - $j - 1])
$min = $arr[$i][$n - $j - 1];
if ($max< $arr[$i][$j])
$max = $arr[$i][$j];
}
else
{
if ($min > $arr[$i][$j])
$min = $arr[$i][$j];
if ($max < $arr[$i][$n - $j - 1])
$max = $arr[$i][$n - $j - 1];
}
}
}
echo "Maximum = " , $max
,", Minimum = " , $min;
}
// Driver Code
$arr = array(array(5, 9, 11),
array(25, 0, 14),
array(21, 6, 4));
maxMin($arr, 3);
// This code is contributed by anuj_67.
?>
JavaScript
<script>
// Javascript program for finding maximum
// and minimum in a matrix.
let MAX = 100;
// Finds maximum and minimum
// in arr[0..n-1][0..n-1]
// using pair wise comparisons
function maxMin(arr,n)
{
let min = +2147483647;
let max = -2147483648;
// Traverses rows one by one
for(let i = 0; i < n; i++)
{
for(let j = 0; j <= n / 2; j++)
{
// Compare elements from beginning
// and end of current row
if (arr[i][j] > arr[i][n - j - 1])
{
if (min > arr[i][n - j - 1])
min = arr[i][n - j - 1];
if (max< arr[i][j])
max = arr[i][j];
}
else
{
if (min > arr[i][j])
min = arr[i][j];
if (max < arr[i][n - j - 1])
max = arr[i][n - j - 1];
}
}
}
document.write("Maximum = " + max +
", Minimum = " + min);
}
// Driver Code
let arr = [ [ 5, 9, 11 ],
[ 25, 0, 14 ],
[ 21, 6, 4 ] ];
maxMin(arr, 3);
// This code is contributed by sravan kumar
</script>
OutputMaximum = 11, Minimum = 0
Time complexity: O(n2).
Auxiliary Space: O(1), since no extra space has been taken.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read