• + 0 comments

    Swift Solution :-

    func hourglassSum(arr: [[Int]]) -> Int {
        // Write your code here
            var maxSum: Int?
            for rowIndex in 1..<5 {
                for elementIndex in 1..<5 {
                    let upperRow = arr[rowIndex-1]
                    let currentRow = arr[rowIndex]
                    let lowerRow = arr[rowIndex+1]
                    let sum = upperRow[elementIndex-1] + upperRow[elementIndex] + upperRow[elementIndex+1] + currentRow[elementIndex] + lowerRow[elementIndex-1] + lowerRow[elementIndex] + lowerRow[elementIndex+1]
                    if maxSum == nil {
                        maxSum = sum
                    } else if let maxSumLocal = maxSum, maxSumLocal < sum {
                        maxSum = sum
                    } else {
                        continue
                    }
                }
            }
            return maxSum ?? 0
    }