Diagonal Difference

Sort by

recency

|

5764 Discussions

|

  • + 0 comments

    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]

    return abs(primary_diagonal_sum - secondary_diagonal_sum)
    
  • + 0 comments

    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); }
    }

    `

  • + 0 comments

    Solution TypeScript:

     let result = 0
     for(let i = 0; i< arr.length; i++){
          result+= (arr[i][i] - arr[i][(arr.length - 1) - i])
     }
     return Math.abs(result)
    
  • + 0 comments

    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); }

  • + 0 comments
        public static int diagonalDifference(List<List<Integer>> arr) {
            // Write your code here
            int n = arr.size();
            
            int total = 0;
            for (int i = 0; i < n; i++) {
                // int left = arr.get(i).get(i);
                // int right = arr.get(i).get(n - 1 - i);
                // total += (left - right);
                total += arr.get(i).get(i) - arr.get(i).get(n - 1 - i);
            }
            
            return Math.abs(total);
        }