Maximum trace possible for any sub | C ++ implementation of the approach ; Function to return the maximum trace possible for a sub - matrix of the given matrix ; Calculate the trace for each of the sub - matrix with top left corner at cell ( r , s ) ; Update the maximum trace ; Return the maximum trace ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N  3 NEW_LINE 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 ; }