Maximum trace possible for any sub | Python 3 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
N = 3 NEW_LINE def MaxTraceSub ( mat ) : NEW_LINE INDENT max_trace = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT r = i NEW_LINE s = j NEW_LINE trace = 0 NEW_LINE while ( r < N and s < N ) : NEW_LINE INDENT trace += mat [ r ] NEW_LINE r += 1 NEW_LINE s += 1 NEW_LINE max_trace = max ( trace , max_trace ) NEW_LINE DEDENT DEDENT DEDENT return max_trace NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 10 , 2 , 5 ] , [ 6 , 10 , 4 ] , [ 2 , 7 , - 10 ] ] NEW_LINE print ( MaxTraceSub ( mat ) ) NEW_LINE DEDENT