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. }
Please click on the like button if it worked

Solution not working or have any suggestions? Please send an email to [email protected]


donate a cup of tea :)


Join Our Facebook Group

Share this solution






codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube