• + 0 comments

    C# SOLUTION

    Brief explanation it checks both the row and column count since there could be more than 6 in either, added guards just in case. For the maxHourglassRow and maxHourglassCol I remove the first and last position a long side with one more for indexing giving to a total of 3 hence the maxHourglassRow - 3 (The exercise has 6 numbers, so if I remove 3, I am left with 3 indexing starts with 0 and I want to start counting to sum them i.e. row[0][0], row[0][1], row[0][2] <- the 0, 1 , 2 represent a column in a 2 dimensional array). In the sum I reused a method to sum the 3 columns from the top of the hourglass and the bottom as well, any comment is welcomed. I believe there could be improvements but for now this is what I came up with.

    public static int hourglassSum(List<List<int>> arr)
        {
            int rowCount = arr.Count;
            
            if (rowCount == 0)
            {
                throw new ArgumentException(); 
            }
    				
            int colCount = arr[0].Count;
    				
            if (colCount == 0)
            {
                throw new ArgumentException(); 
            }
    				
            List<int> finalSumArray = [];
            int maxHourglassRow = rowCount - 3;
            int maxHourglassCol = colCount - 3;
            for (var r = 0; r <= maxHourglassRow; r++) {
                for (var c = 0; c <= maxHourglassCol; c++) {
                    List<int> firstRow = arr[r];
                    List<int> secondRow = arr[r + 1];
                    List<int> thirdRow = arr[r + 2];
                    finalSumArray.Add(rowSum(firstRow, c) + secondRow[c + 1] + rowSum(thirdRow, c));
                } 
            }
            return finalSumArray.Max();
    		}
        
        public static int rowSum(List<int> row, int column)
        {
            int secondColumn = column + 1;
            int thirdColumn = column + 2;
            return row[column] + row[secondColumn] + row[thirdColumn];
        }