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
|
5764 Discussions
|
Please Login in order to post a comment
def diagonalDifference(arr): primary_diagonal_sum = 0 secondary_diagonal_sum = 0 n = len(arr) for i in range(n): primary_diagonal_sum += arr[i][i] secondary_diagonal_sum += arr[i][n - 1 - i]
Extremely slow but easy to understand for newbies
`public static int diagonalDifference(List> arr){ // Write your code here int ans = 0; int left_sum = 0; int right_sum = 0; //left_sum - first for(int i = 0; i < arr.size(); i++){ for(int j = i ; j < arr.get(i).size(); j++){ left_sum += arr.get(i).get(j); break; } } for(int i = 0; i < arr.size(); i++){ for(int j = arr.get(i).size()-1 - i ; j >= arr.get(i).size()-1-i; j--){ right_sum += arr.get(i).get(j); break; } } return Math.abs(left_sum - right_sum); }
}
`
Solution TypeScript:
C#:
> public static int diagonalDifference(List> arr) { var x1 = 0; var x2 = arr.Count() - 1; var sum1 = 0; var sum2 = 0; foreach (List j in arr){ sum1 += j[x1]; sum2 += j[x2]; x1++; x2--; } return Math.Abs(sum1-sum2); }