(919) 964-9842
(919) 964-9842

Hackerrank with PHP: 2D Array - DS

I've been doing coding challenges on Hackerrank after not doing so great on a code test. They definitely get you thinking outside the normal, everyday work situations I face during my full-time job. As I find solutions, I am posting them here in case someone else is stuck. I code primarily in PHP, so that's what my solutions will be in.

Here's the problem below.

There are 16 hourglasses in $arr, and an hourglass sum is the sum of an hourglass' values. Calculate the hourglass sum for every hourglass in $arr, then print the maximum hourglass sum.

Complete the function hourglassSum in the editor below. It should return an integer, the maximum hourglass sum in the array.

hourglassSum has the following parameter(s):

arr: an array of integers

1
2
3
4
5
6
7
8
9
10
11
12
// Complete the hourglassSum function below.
function hourglassSum($arr) {
    for($i = 0; $i <= count($arr) - 3; $i++) {
        for($j = 0; $j <= count($arr[$i]) - 3; $j++) {
            $result[] = intval($arr[$i][$j] + $arr[$i][$j+1] + $arr[$i][$j+2]
                + $arr[$i+1][$j+1]
                + $arr[$i+2][$j] + $arr[$i+2][$j+1] + $arr[$i+2][$j+2]);
        }
    }

    return max($result);
}
Categories: Development

Leave a Reply

Your email address will not be published. Required fields are marked *