Wednesday 20 April 2016

Hourglass Sum Hacker Rank problem solution

HourGlass Sum problem:

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.

Solution:

My solution works with iterative approach as of now. I am preparing a solution with recursive as well. 

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 arr[][] = new int[6][6];
        for(int i=0; i < 6; i++){
            for(int j=0; j < 6; j++){
                arr[i][j] = in.nextInt();
            }
        }
        
        int max = Integer.MIN_VALUE;
for (int i = 2; i < 6; i++) {
for (int j = 2; j < 6; j++) {
int sum = 0;
for (int k = i - 2; k <= i; k++) {
for (int l = j - 2; l <= j; l++) {
if (k == i - 1 && l != j - 1) {
sum = sum + 0;
} else {
sum = sum + arr[k][l];
}
}
}
if (sum > max) {
max = sum;
}
}
}

System.out.println(max);
    }
}