Diagonal Difference

Sort by

recency

|

318 Discussions

|

  • + 0 comments

    c++

    int diagonalDifference(vector<vector<int>> arr) {
        int result = 0;
        for(int i = 0; i < arr.size(); ++i){
            vector<int> const& row = arr[i];
            result += row[i] - row[row.size() - i - 1];
        }
        return std::abs(result);
    }
    
  • + 0 comments

    Rust

    fn diagonalDifference(arr: &[Vec<i32>]) -> i32 {
       let n = arr.len();
    
        let mut left2right = 0;
        let mut right2left = 0;
        for i in 0..n {
            left2right += *arr[i as usize].get(i as usize).unwrap();
            right2left += *arr[i as usize].get(n - 1 - i as usize).unwrap();
        }
    
        (left2right - right2left).abs()
    }
    
  • + 0 comments

    Python solution

    def diagonalDifference(arr):
        d1 = d2 = 0
        
        for i in range(0, len(arr)):
            d1 += arr[i][i]
            d2 += arr[i][len(arr) - i - 1]
    
        return abs(d1 - d2)
    
  • + 0 comments
    # Write your code here
    principal = 0
    secondary = 0
    n = len(arr)
    
    for i in range(0, n):
    		principal+=arr[i][i]
    		secondary+=arr[i][n-i-1]
    
    absDiff = abs(principal-secondary)
    return absDiff
    

    undefined

  • + 0 comments

    Java Solution:

        public static int diagonalDifference(List<List<Integer>> arr) {
    
            int leftSum = 0;
            int rightSum = 0;
            
            for(int i=0; i<arr.size();i++){
                List<Integer> row = arr.get(i);
                leftSum = leftSum + row.get(i);
                rightSum = rightSum + row.get(row.size() -1  - i);
            }
            
            return leftSum > rightSum ? (leftSum - rightSum) : (rightSum - leftSum);
        }