Thursday, 26 May 2016

Hackarank 2D Array GlassHour Problem - Java Solution


Hello Coders,
I am posting this code for my future reference.
Below is the problem statement!

Task
Calculate the hourglass sum for every hourglass in , then print the maximum hourglass sum.
Input Format
There are  lines of input, where each line contains  space-separated integers describing 2D Array ; every value in will be in the inclusive range of  to .
Constraints
Output Format
Print the largest (maximum) hourglass sum found in .
Sample Input
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0
Sample Output
19


Solution: 



import java.io.*;

import java.util.*;

import java.text.*;

import java.math.*;

import java.util.regex.*;



public class Solution {



    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        int a[][] = new int[6][6];

      

        int temp_sum,sum = -1000000;

      

        for(int i=0; i < 6; i++){

            for(int j=0; j < 6; j++){

                a[i][j] = in.nextInt();

            }

        }

  

    for(int i=0;i<4;i++){

        for(int j=0;j<4;j++){

          

            temp_sum=a[i][j]+a[i][j+1]+a[i][j+2]+a[i+1][j+1]+a[i+2][j]+a[i+2][j+1]+a[i+2][j+2];

      

            if (temp_sum >= sum) {

      sum = temp_sum;

     }     

          

        }

      

    }

    System.out.println(sum);

    }

}



Simple but elegant!


Thanks For being with Us plz Like us On Fb==> computer Stuffs <==

Blog Top Sites

Share Our Badge

 Computer Stuffs

Be Updated Its Free.

Subscribe via Email

Visitors Everyday



Followers