Diagonal Difference

Sort by

recency

|

638 Discussions

|

  • + 0 comments

    public static int diagonalDifference(List> arr) { // Write your code here

    int primaryDiagnolSum =0;
    int secondaryDiagnolSum =0;
    

    for(int i=1; i<=arr.size();i++) { List intArray = arr.get(i-1); primaryDiagnolSum+=intArray.get(i-1); secondaryDiagnolSum+= intArray.get(arr.size()-i);

    }

    int difference = primaryDiagnolSum-secondaryDiagnolSum; return (difference<0)?difference*-1: difference;

    }
    
  • + 0 comments

    Java 8 solution

    public static int diagonalDifference(List<List<Integer>> arr) {
    // Write your code here
            int sumElementLeftToRightDiagonal= IntStream
                .range(0,arr.size())
                .mapToObj(i->arr.get(i).get(i))
                .collect(toList())
                .stream()
                .reduce(0,Integer::sum);
    
        int sumElementRightToLeftDiagonal=IntStream
                .range(0, arr.size())
                .mapToObj(i->arr.get(i).get(arr.size()-1-i))
                .collect(toList())
                .stream()
                .reduce(0,Integer::sum);
    
        return Math.abs(sumElementLeftToRightDiagonal-sumElementRightToLeftDiagonal);
    
    }
    
  • + 0 comments

    Python solution

    from functools import reduce
    import operator
    
    def diagonalDifference(arr):
        # Write your code here
        size = len(arr)
        return abs(reduce(operator.add, [arr[x][x] - arr[x][size-1-x] for x in range(size)]))
    
  • + 0 comments

    My solution in C++

    int diagonalDifference(vector<vector<int>> arr) {
    int left_result = 0;
    int right_result = 0;
    int diagonalDiff = 0; 
    for (int i = 0; i < arr.size(); i++){
         
      left_result += arr[i][i];
      right_result += arr[i][arr.size()-i-1];
    }
    
    diagonalDiff = left_result - right_result;
    return abs(diagonalDiff);
    }
    
  • + 0 comments

    My submission is Below: Please give inputs about the approach

     public static int diagonalDifference(List<List<Integer>> arr) {
        // Write your code here
        int countp=0,counts =0;
            for(int i=0,j=arr.size()-1;i<arr.size()&&j>=0;i++,j--){
                countp = countp + arr.get(i).get(i);
                counts= counts + arr.get(i).get(j);
            }
            if(countp<=counts){
                return counts-countp;
            }else{
                return countp-counts;
            }
        }