Find number of Positional Elements in C++

C++Server Side ProgrammingProgramming

In this problem, we are given two dimensional arrays mat[n][m]. Our task is to find the number of positional elements.

An element is said to be a positional element if the element is either maximum or minimum element of the row or column.

Let’s take an example to understand the problem,

Input

mat[][] = {2, 5, 7}
{1, 3, 4}
{5, 1, 3}

Output

8

Explanation

Elements 2, 5, 7, 1, 4, 5, 1, 3 are positional elements.

Solution Approach

A simple solution to the problem is by storing the maximum and minimum element of each row and column. And then check for the condition and count the number.

Program to illustrate the working of our solution,

Example

 Live Demo

#include <iostream>
using namespace std;
const int MAX = 100;
int countAllPositionalElements(int mat[][MAX], int m, int n){
   int rowmax[m], rowmin[m];
   int colmax[n], colmin[n];
   for (int i = 0; i < m; i++) {
      int rminn = 10000;
      int rmaxx = -10000;
      for (int j = 0; j < n; j++) {
         if (mat[i][j] > rmaxx)
            rmaxx = mat[i][j];
         if (mat[i][j] < rminn)
            rminn = mat[i][j];
      }
      rowmax[i] = rmaxx;
      rowmin[i] = rminn;
   }
   for (int j = 0; j < n; j++) {
      int cminn = 10000;
      int cmaxx = -10000;
      for (int i = 0; i < m; i++) {
         if (mat[i][j] > cmaxx)
            cmaxx = mat[i][j];
         if (mat[i][j] < cminn)
            cminn = mat[i][j];
      }
      colmax[j] = cmaxx;
      colmin[j] = cminn;
   }
   int positionalCount = 0;
   for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
         if ((mat[i][j] == rowmax[i]) || (mat[i][j] ==
            rowmin[i]) || (mat[i][j] == colmax[j]) || (mat[i][j] == colmin[j])){
            positionalCount++;
         }
      }
   }
   return positionalCount;
}
int main(){
   int mat[][MAX] = {
      { 2, 5, 7 },
      { 1, 3, 4 },
      { 5, 1, 3 }
   };
   int m = 3, n = 3;
   cout<<"Number of positional elements is "<<countAllPositionalElements(mat, m, n);
   return 0;
}

Output

Number of positional elements is 8
raja
Published on 15-Mar-2021 10:56:40
Advertisements