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 ; Given matrix ; Given dimension
function MaximumSum ( arr , n ) { let ans = 0 ; for ( let i = 0 ; i < n ; i ++ ) { let x = 0 , y = i , sum = 0 ; for ( let j = i ; j < n ; j ++ ) { sum += arr [ x ++ ] [ y ++ ] ; } if ( sum > ans ) ans = sum ; } for ( let i = 1 ; i < n ; i ++ ) { let x = i , y = 0 , sum = 0 ; for ( let j = i ; j < n ; j ++ ) { sum += arr [ x ++ ] [ y ++ ] ; } if ( sum > ans ) ans = sum ; } return ans ; } let arr = [ [ 1 , 2 , 3 ] , [ 3 , 5 , 10 ] , [ 1 , 3 , 5 ] ] ; let n = arr . length ; document . write ( MaximumSum ( arr , n ) ) ;