HackerRank Java- 2D Array



The sum of an hourglass is the sum of all the numbers within it. The sum for the hourglasses above are 7, 4, and 2, respectively.

In this problem you have to print the largest sum among all the hourglasses in the array.



  1. import java.io.*;
  2. import java.math.*;
  3. import java.security.*;
  4. import java.text.*;
  5. import java.util.*;
  6. import java.util.concurrent.*;
  7. import java.util.regex.*;
  8. public class Solution {
  9. public static void main(String[] args) {
  10. Scanner sc = new Scanner(System.in);
  11. int[][] a = new int[6][6];
  12. int max = Integer.MIN_VALUE;
  13. for (int i = 0; i < 6; i++) {
  14. for (int j = 0; j < 6; j++) {
  15. a[i][j] = sc.nextInt();
  16. if (i > 1 && j > 1) {
  17. int sum = a[i][j]
  18. + a[i][j - 1]
  19. + a[i][j - 2]
  20. + a[i - 1][j - 1]
  21. + a[i - 2][j]
  22. + a[i - 2][j - 1]
  23. + a[i - 2][j - 2];
  24. if (sum > max)
  25. max = sum;
  26. }
  27. }
  28. }
  29. sc.close();
  30. System.out.println(max);
  31. }
  32. }

download android app