# 2D Array – DS Hackerrank problem solution

##### 2D Array – DS Hackerrank

Context
Given a 6X6 2D Array, A:

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

We define an hourglass in A to be a subset of values with indices falling in this pattern in A’s graphical representation:

a b c
d
e f g

There are 16 hourglasses in A, and an hourglass sum is the sum of an hourglass’ values.

Calculate the hourglass sum for every hourglass in A, then print the maximum hourglass sum.

Input Format

There are 6 lines of input, where each line contains 6 space-separated integers describing 2D Array A; every value in A will be in the inclusive range of -9 to 9.

Constraints

-9<=A[i][j]<=9 0<=i<=j<=5 Output Format

Print the largest (maximum) hourglass sum found in A.

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

contains the following hourglasses:

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

0 1 0 1 0 0 0 0 0 0 0 0
1 1 0 0
0 0 2 0 2 4 2 4 4 4 4 0

1 1 1 1 1 0 1 0 0 0 0 0
0 2 4 4
0 0 0 0 0 2 0 2 0 2 0 0

0 0 2 0 2 4 2 4 4 4 4 0
0 0 2 0
0 0 1 0 1 2 1 2 4 2 4 0

The hourglass with the maximum sum (19) is:

2 4 4
2
1 2 4

##### Solution
```#include <iostream>

using namespace std;

int main(){
int a,ar;
for(int arr_i = 0;arr_i < 6;arr_i++){
for(int arr_j = 0;arr_j < 6;arr_j++){
cin >> a[arr_i][arr_j];
}
}
int max=-63;
for( int i=0; i<4; i++){
for( int j=0; j<4; j++){
ar=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(ar>max)
max=ar;
}
}
cout<<max;
return 0;
}
```
``````import java.util.Scanner;

public class Main {

public static void main(String[] args) {

int numbers[][] = new int;

Scanner in = new Scanner(System.in);

for (int i = 0; i < 6; i++){
for (int j = 0; j < 6; j++){
numbers[i][j] = in.nextInt();
}
}

int currentHourGlass;
int largestSum = -999;

for (int i = 1; i < 5; i++){
for (int j = 1; j < 5; j++){
currentHourGlass = 0;
currentHourGlass += numbers[i-1][j-1];
currentHourGlass += numbers[i-1][j];
currentHourGlass += numbers[i-1][j+1];
currentHourGlass += numbers[i][j];
currentHourGlass += numbers[i+1][j-1];
currentHourGlass += numbers[i+1][j];
currentHourGlass += numbers[i+1][j+1];
if (currentHourGlass > largestSum){
largestSum = currentHourGlass;
}

}
}

System.out.printf("%d", largestSum);

}
}
``````

### hasectic

A web developer(Front end and Back end), and DBA at csdamu.com. Currently working as Salesforce Developer @ Tech Matrix IT Consulting Private Limited. Check me @about.me/s.saifi