Skip to main content

Command Palette

Search for a command to run...

Maximum Sum of an Hourglass

Published
2 min read
Maximum Sum of an Hourglass
G

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.

I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.

You are given an m x n integer matrix grid.

We define an hourglass as a part of the matrix with the following form:

LeetCode Problem - 2428

class Solution {
    public int maxSum(int[][] grid) {
        // Get the number of rows (m) and columns (n) in the grid
        int m = grid.length, n = grid[0].length;

        // Initialize max to the smallest possible integer value to track the maximum hourglass sum
        int max = Integer.MIN_VALUE;

        // Traverse the grid up to the last possible hourglass start position
        for(int i = 0; i <= m - 3; i++) {
            for(int j = 1; j < n - 1; j++) {
                // Calculate the hourglass sum centered at grid[i+1][j] and update max if it's larger
                max = Math.max(max, hourglass(grid, i, j));
            }
        }

        // Return the maximum hourglass sum found
        return max;
    }

    // Helper method to calculate the hourglass sum for the hourglass centered at grid[i+1][j]
    private int hourglass(int[][] grid, int i, int j) {
        // Calculate the sum of the top row of the hourglass
        int top = grid[i][j-1] + grid[i][j] + grid[i][j+1];

        // Get the value of the middle element of the hourglass
        int mid = grid[i+1][j];

        // Calculate the sum of the bottom row of the hourglass
        int bottom = grid[i+2][j-1] + grid[i+2][j] + grid[i+2][j+1];

        // Return the total sum of the hourglass
        return top + mid + bottom;
    }
}

More from this blog

S

Software and Performance Testing Insights

462 posts

Results-Driven Agile QA Specialist | Expert in Mobile & Web Testing | Proficient in Test Planning, Execution, and Root Cause Analysis.