Maximize sum by traversing diagonally from each cell of a given Matrix | Function to find the maximum sum ; Loop to traverse through the upper triangular matrix and update the maximum sum to ans ; Traverse through the lower triangular matrix ; Driver Code ; Given matrix ; Given dimension
def MaximumSum ( arr , n ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT x , y , sum = 0 , i , 0 NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT sum , x , y = sum + arr [ x ] [ y ] , x + 1 , y + 1 NEW_LINE DEDENT if ( sum > ans ) : NEW_LINE INDENT ans = sum NEW_LINE DEDENT DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT x , y , sum = i , 0 , 0 NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT sum , x , y = sum + arr [ x ] [ y ] , x + 1 , y + 1 NEW_LINE DEDENT if ( sum > ans ) : NEW_LINE INDENT ans = sum NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 1 , 2 , 3 ] , [ 3 , 5 , 10 ] , [ 1 , 3 , 5 ] ] NEW_LINE n = len ( arr ) NEW_LINE print ( MaximumSum ( arr , n ) ) NEW_LINE DEDENT