728x90
Problem
https://www.hackerrank.com/challenges/diagonal-difference/problem?isFullScreen=true&h_r=next-challenge&h_v=zen
Approach
So absolute difference can be calculated like this sum(left to right) - sum(right to left). I was thinking maybe I can calculate both sides at the same time. But I just found easier way by doing loop two times.
Solution
function diagonalDifference(arr) {
const length = arr[0].length;
let result = 0;
// add from left top to right bottom
for(let i = 0; i < length; i++) {
result += arr[i][i];
}
// deduct from right top to left bottom
for(let j = 0; j < length; j++) {
result -= arr[j][length-1-j];
}
// return absolute number
return Math.abs(result);
}
728x90
'Research > Coding Test' 카테고리의 다른 글
HackerRank_Staircase (0) | 2023.04.02 |
---|---|
HackerRank_Plus Minus (0) | 2023.04.02 |
leetcode_66. plus-one (0) | 2023.03.24 |
747. Largest Number At Least Twice of Others (0) | 2023.03.23 |
스택/큐_기능개발 (0) | 2023.03.21 |
댓글