Skip to content

Instantly share code, notes, and snippets.

@davidon
Last active December 13, 2018 11:56
Show Gist options
  • Save davidon/f3818cf3868764a9a388c33b3226e49e to your computer and use it in GitHub Desktop.
Save davidon/f3818cf3868764a9a388c33b3226e49e to your computer and use it in GitHub Desktop.
https://www.hackerrank.com/challenges/2d-array/problem ; Given a 2D Array, find the maximum hourglass sum of all 16 hourglasses
using System.IO;
using System;
class Solution {
// Complete the hourglassSum function below.
static int hourglassSum(int[][] arr) {
int[] sum = new int[16];
int k = 0;
for (int i = 0; i <= 3; i++)
{
for (int j = 0; j <= 3; j++)
{
int ia = i + 1; //[ia, ja] is the middle of hourglass
int ja = j + 1;
sum[k] = arr[ia][ja] + arr[ia - 1][ja] + arr[ia-1][ja-1] + arr[ia-1][ja + 1] + arr[ia + 1][ja] + arr[ia + 1][ja - 1] + arr[ia + 1][ja + 1];
k++;
}
}
Array.Sort(sum);
return sum[15];
}
static void Main(string[] args) {
TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
int[][] arr = new int[6][];
for (int i = 0; i < 6; i++) {
arr[i] = Array.ConvertAll(Console.ReadLine().Split(' '), arrTemp => Convert.ToInt32(arrTemp));
}
int result = hourglassSum(arr);
textWriter.WriteLine(result);
textWriter.Flush();
textWriter.Close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment