Maximum Path Sum in a Grid
Updated
Problem statement
You are given an m x n grid of integers grid. Each path walks from grid[0][0], the corner cell in the first row and first column, to grid[m - 1][n - 1], the corner cell in the last row and last column, and every move goes one cell to the right or one cell down.
A path's sum adds up the numbers in all of its cells, both corner cells included. Some numbers can be negative, and every path must still finish at the bottom-right corner.
Return the largest sum that any path can reach.
Function
maxPathSum(grid: int[][]) → intExamples
Example 1
grid = [[5,1,-4,2],[3,-2,6,1],[-1,4,2,7]]return = 21The best path goes down from 5 to 3, right through -2 to 6, down to 2 and right to 7; its sum is 21. It accepts the -2 to reach the 6. Making both down moves at the start instead, 5, 3, -1, 4, 2, 7, avoids the -2 but adds up to 20.
Example 2
grid = [[-3,4,-1,2]]return = 2With one row there is just one path, and it walks right over every cell: -3 + 4 + (-1) + 2 = 2.
Example 3
grid = [[-5,-2],[-4,-1]]return = -8Every number is negative. Through the -2 the sum is -5 + (-2) + (-1) = -8; through the -4 it is -5 + (-4) + (-1) = -10. The answer is -8.
Constraints
m == grid.lengthn == grid[i].length1 <= m, n <= 200-1000 <= grid[i][j] <= 1000
More Zillow Onsite Interview questions
- Valid ParenthesesPHONE SCREEN · ONSITE INTERVIEW · Seen Jul 2025
- Build a Hash TablePHONE SCREEN · ONSITE INTERVIEW · Seen Feb 2023
- Spiral MatrixPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2022
- First Subarray with the Largest SumOA · ONSITE INTERVIEW · Seen Aug 2021
- Count Duplicate CharactersONSITE INTERVIEW · Seen Oct 2020
- Decision Tree Classifier from ScratchONSITE INTERVIEW · Seen Nov 2019
- Find Median from Data StreamPHONE SCREEN · ONSITE INTERVIEW · Seen Jul 2018
- LRU CachePHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2016
- Tic-Tac-Toe Winner on a Huge BoardPHONE SCREEN · ONSITE INTERVIEW · Seen Sep 2016
- Most Frequent Three-Page SequencesPHONE SCREEN · ONSITE INTERVIEW · Seen Aug 2016
Similar questions at other companies
- Assign Escalations to TeamsAmazon · ONSITE INTERVIEW
- Maximum All-Ones Square Side LengthOmnissa · ONSITE INTERVIEWOmnissa interview questions
- Minimum Path SumMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- Minimum Path SumBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions
- Bomb Enemy Best CoordinatesSambaNova Systems · ONSITE INTERVIEWSambaNova Systems interview questions
- Largest Square of Ones in a GridExpedia · ONSITE INTERVIEWExpedia interview questions
- Longest Increasing Path in a MatrixNew Relic · PHONE SCREEN · ONSITE INTERVIEW
- Longest Increasing Path in a MatrixVisa · ONSITE INTERVIEWVisa interview questions
- Maximal Rectangle in a Binary MatrixGoogle · ONSITE INTERVIEWGoogle interview questions
- Find Robots by Blocker DistancesUber · PHONE SCREENUber interview questions