We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Algorithms
- Warmup
- Diagonal Difference
- Discussions
Diagonal Difference
Diagonal Difference
Sort by
recency
|
5587 Discussions
|
Please Login in order to post a comment
`def diagonalDifference(arr) primary_diagonal_sum = (0...arr.size).inject(0) { |sum, n| sum + arr[n][n] } secondary_diagonal_sum = (0...arr.size).inject(0) { |sum, i| sum + arr[i][-i-1] }
end`
def diagonalDifference(arr): x = 0 y = 0 for i in range(n): x += arr[i][i] y += arr[i][-(1+i)] return abs(x-y)
at least this works lol i dont do coding
python3
def diagonalDifference(arr): sum1 = 0 sum2 = 0 for i in range(n): sum1 = sum1 +arr[i][i] sum2 = sum2 + arr[i][(n-1)-i] diff = abs(sum1 - sum2) return(diff)
C++ without array approach
It relies on the fact that for each element in the first diagonal, the index difference (starting from 0) is a = matrixSize + 1 and on the second diagonal, the index difference between each element is b = matrixSize - 1.
The "j != 0 && j != (size * size) - 1" in the second if statement checks if the current index is not the first or the last, because these indexes are always multiples of both a and b, which causes superfluous addition to b.