ProblemSolving

# Hacker Rank Problem Java Find Max Sum of Hourglass in 2D Array Solution

You are given a 6 * 6  2D array. An hourglass in an array is a portion shaped like this:

a b c
d
e f g

For example, if we create an hourglass using the number 1 within an array full of zeros, it may look like this:

1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0

Actually, there are many hourglasses in the array above. The three leftmost hourglasses are the following:

1 1 1     1 1 0     1 0 0
1         0         0
1 1 1     1 1 0     1 0 0

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.

Input Format

There will be exactly 6  lines, each containing 6 integers seperated by spaces. Each integer will be between -9 and 9 inclusive.

Output Fromat

Print the answer to this problem on a single line.

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


Explanation

The hourglass which has the largest sum is:

2 4 4
2
1 2 4

Solution.java:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
public static int getarraysum(int[][] a,int ele_row_i,int ele_col_i)
{
int sum=0;
//neglect fst
int fst_row=ele_row_i+1;
int fst_col=ele_col_i;
//neglect_scnd
int sec_row=ele_row_i+1;
int sec_col=ele_col_i+2;

for(int i=ele_row_i;i<ele_row_i+3;i++){
for(int j=ele_col_i;j<ele_col_i+3;j++){
if(i==fst_row && j==fst_col || i==sec_row && j==sec_col){
continue;
}else{
sum=sum+(int)a[i][j];
}
}
}//end for
return sum;
}

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int arr[][] = new int;
int flag_invalid_entry=0;
int max_hour_sum=0;

//input
for(int i=0; i < 6; i++){
for(int j=0; j < 6; j++){
arr[i][j] = in.nextInt();
if(arr[i][j]<-9 || arr[i][j]>9){
flag_invalid_entry=1;
}
}
}

if(flag_invalid_entry==0){
for(int i=0;i<=3;i++){
for(int j=0;j<=3;j++){
int new_sum=getarraysum(arr,i,j);
if(max_hour_sum==0 && flag_invalid_entry==0){
max_hour_sum=max_hour_sum+new_sum;
flag_invalid_entry=1;
}else if(max_hour_sum<new_sum){
max_hour_sum=new_sum;
}

//System.out.println(new_sum+":sum of hourglass,"+arr[i][j]+" i:"+ i +" j:" + j+"updated_sum:"+max_hour_sum);
}
}
}

System.out.println(""+max_hour_sum);
}
}



Thank You.

## 2 thoughts on “Hacker Rank Problem Java Find Max Sum of Hourglass in 2D Array Solution”

1. best pron says:

nI6MkG It as amazing for me to have a web page, which is good in support of my knowledge. thanks admin

2. best pron says:

S9AQ0o Nice blog here! Also your website loads up fast! What web host are you using? Can I get your affiliate link to your host? I wish my web site loaded up as fast as yours lol