Maximum trace possible for any sub | PHP 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
< ? php $ N = 3 ; function MaxTraceSub ( $ mat ) { global $ N ; $ max_trace = 0 ; for ( $ i = 0 ; $ i < $ N ; $ i ++ ) { for ( $ j = 0 ; $ j < $ N ; $ j ++ ) { $ 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 ; } $ mat = array ( array ( 10 , 2 , 5 ) , array ( 6 , 10 , 4 ) , array ( 2 , 7 , -10 ) ) ; print ( MaxTraceSub ( $ mat ) ) ; ? >