Diagonal Difference

Sort by

recency

|

648 Discussions

|

  • + 0 comments

    no need to two variables to calculate result. In Java public static int diagonalDifference(List> arr) { int n = arr.size(); int result =0; for (int i = 0; i < n; i++) { result += arr.get(i).get(i) - arr.get( i).get(n - i -1); } return Math.abs(result); }

  • + 0 comments

    in C

    int diagonalDifference(int arr_rows, int arr_columns, int** arr) {
        
        int LTRsum = 0, RTLsum = 0;
        
        for(int r=0,c=0;r<arr_rows && c<arr_columns;r++,c++){
                        
                    /*LTR*/
                    LTRsum+=arr[r][c];
                    /*RTL*/
                    RTLsum+= arr[r][arr_columns-1-c];
                
        }
        
        if((RTLsum-LTRsum) >= 0){
            return RTLsum-LTRsum;
        }else {
        return  LTRsum-RTLsum;
        }
    }
    
  • + 0 comments

    Draw a 3x3 matrix with a pen and paper, and mark out the corrdinates for each diagonal. Will make it clearer.

  • + 0 comments

    I had a slightly nuanced approach to what most people did, thought I'd share. Python

    def diagonalDifference(arr):
        length = len(arr)
        diff = 0
        for i in range(0, length):
            diff = diff - (arr[i][i] - arr[i][length-(1+i)])
            
        return abs(diff)
    
  • + 0 comments

    Java 8:

    public static int diagonalDifference(List<List<Integer>> arr) {
    int sum1 = 0;
    int sum2 = 0;
        int j = arr.size() - 1;
        for (int i = 0; i < arr.size(); i++) {
            sum1 += arr.get(i).get(i);
            sum2 += arr.get(i).get(j);
            j--;
        }
        return Math.abs(sum1 - sum2);
    }