Maximum trace possible for any sub-matrix of the given matrix in C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to find maximum trace possible for any sub-matrix of the given matrix.

For this we will be provided with N*N matrix. Our task is to find the submatrix having the maximum trace.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
#define N 3
//finding the maximum trace of
//submatrix
int MaxTraceSub(int mat[][N]) {
   int max_trace = 0;
   for (int i = 0; i < N; i++) {
      for (int j = 0; j < N; j++) {
         int r = i, s = j, trace = 0;
            while (r < N && s < N) {
               trace += mat[r][s];
               r++;
               s++;
               max_trace = max(trace, max_trace);
            }
         }
      }
   return max_trace;
}
int main() {
   int mat[N][N] = {
      { 10, 2, 5 },
      { 6, 10, 4 },
      { 2, 7, -10 } };
   cout << MaxTraceSub(mat);
   return 0;
}

Output

20
raja
Published on 27-Jul-2020 11:57:10
Advertisements