Diagonal Difference

  • + 7 comments

    The same exact solution is easily accomplished in Java, but it still relies on saving unneeded values to an array which, as has already been pointed out, is actually a less optimal solution because it needlessly stores n^2 - 2n integers in arrays. Java equivalent of this python solution:

    public Solution(){
        Scanner scan = new Scanner(System.in);
        int n = Integer.parseInt(scan.nextLine());
        int sumOne = 0;
        int sumTwo = 0;
    
        for(int currentOne = 0, currentTwo = n - 1; 
                currentOne < n; 
                currentOne ++, currentTwo--
           ){ 
                String[] inputLine = scan.nextLine().split(" ");
    
                sumOne = sumOne 
                + Integer.parseInt(inputLine[currentOne]);
                sumTwo = sumTwo 
                + Integer.parseInt(inputLine[currentTwo]);
        }
        System.out.println(Math.abs(sumOne - sumTwo));
    }
    
    public static void main(String[] args) {
        Solution s = new Solution();
    }