BackeasyDynamic ProgrammingCognizantPhonePe

Optimal Grid Path Protocol 9 Solution

Problem Statement

You are given a grid of size N x N. Your task is to find the maximum value that can be obtained by moving either right or down from each cell in the grid.

Example 1
Input
N = 3, grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output
9

Explanation: Step-by-step: We initialize a 2D array dp of size (N+1) x (N+1) with all values set to 0. We iterate over the grid and for each cell, we calculate the maximum value that can be obtained by moving either right or down from the cell. The maximum value is the maximum of the current cell's value and the maximum values of the cell above it and the cell to its left. We update the dp array with these values. Finally, we return the maximum value in the dp array, which represents the optimal grid path.

Example 2
Input
N = 4, grid = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
Output
16

Explanation: Step-by-step: We initialize a 2D array dp of size (N+1) x (N+1) with all values set to 0. We iterate over the grid and for each cell, we calculate the maximum value that can be obtained by moving either right or down from the cell. The maximum value is the maximum of the current cell's value and the maximum values of the cell above it and the cell to its left. We update the dp array with these values. Finally, we return the maximum value in the dp array, which represents the optimal grid path.

Constraints

  • 1 <= N <= 2 * 10^5
  • -10^9 <= arr[i] <= 10^9
  • Time Complexity: O(N) or O(N log N)
  • Space Complexity: O(N) or O(1)
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Optimal Grid Path Protocol 9 — Problem Statement & Solution Guide

Dynamic ProgrammingEasyBitmask DP
TimeO(N^2)
|
SpaceO(N)

Problem Description

You are given a grid of size N x N. Your task is to find the maximum value that can be obtained by moving either right or down from each cell in the grid.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Optimal Grid Path Protocol 9"

easy

WHY DOES IT MATTER?

The "grid path with restricted moves" pattern is ubiquitous in algorithmic interviews because it tests understanding of DP, optimal substructure, and state compression. Mastery of this pattern enables candidates to solve a wide range of problems, from coin change to edit distance, with confidence.

OPTIMIZATION CHALLENGE

The key insight is that each cell’s value depends only on its immediate top and left neighbors, allowing us to compute the solution in a single pass and discard earlier rows or columns. This reduces the space from O(N^2) to O(N) without affecting time.

REAL-WORLD CONNECTION

In distributed systems, routing packets through a network of nodes with latency costs is analogous to this grid problem. The DP solution mirrors how routers compute shortest paths (e.g., Dijkstra) but in a structured grid where only two directions are allowed, simplifying the state space.

When explaining your solution, emphasize the recurrence first, then show how you can collapse the DP table to a single array. Interviewers appreciate concise reasoning and a clear mapping from the problem statement to the DP formula.

COMPLEXITY AT A GLANCE

⏱ Time:O(N^2)
💾 Space:O(N)

Core Theory — Why This Approach?

Dynamic programming (DP) is the optimal paradigm for grid path problems where the decision at each cell depends only on a small set of previous decisions. In this problem, the maximum value obtainable at cell (i,j) can be expressed as the maximum of the values from its top neighbor (i-1,j) and left neighbor (i,j-1) plus the cell’s own value. This recurrence,

dp[i][j] = grid[i][j] + max(dp[i-1][j], dp[i][j-1]),

captures the optimal substructure: the best path to (i,j) must come from the best path to one of its two predecessors. Naive approaches that enumerate all possible paths (exponential in N) quickly become infeasible as N grows, because the number of paths from the top-left to bottom-right is

C(2N-2, N-1) ~ 4^N / sqrt(N),

which explodes even for moderate N. DP reduces this to a quadratic number of states, each computed in constant time, yielding an O(N^2) time solution. Moreover, the DP table can be compressed to a single row or column, reducing space to O(N).

Interview Questions on This Problem

Q1How would you modify the algorithm if you were allowed to move diagonally as well as right and down?

Add a third predecessor: dp[i][j] = grid[i][j] + max(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]). The recurrence still holds, but the base cases must account for the top row and left column separately. The time complexity remains O(N^2).

Q2A fintech platform needs to compute the maximum profit path in a 1000x1000 grid of transaction fees. What trade-offs would you consider between time and space?

For a 1000x1000 grid, O(N^2) time (≈1e6 operations) is acceptable, but storing a full 2D array uses ~8MB if integers are 8 bytes. Using a single array of size N reduces memory to ~8KB, which is beneficial for memory-constrained environments or when the grid is streamed. The trade-off is a slight increase in code complexity for row-wise updates.

Q3During a coding interview, you realize the interviewer wants you to return the path itself, not just the maximum sum. How would you adapt your DP solution?

Maintain a second 2D array of pointers or directions (e.g., 'U' for up, 'L' for left) that records from which predecessor the maximum was taken. After filling dp, backtrack from (N-1,N-1) using the direction array to reconstruct the path. This adds O(N^2) space for the direction array but keeps time O(N^2).

Examples

Example 1

Input

N = 3, grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Output

9

Explanation: Step-by-step: We initialize a 2D array dp of size (N+1) x (N+1) with all values set to 0. We iterate over the grid and for each cell, we calculate the maximum value that can be obtained by moving either right or down from the cell. The maximum value is the maximum of the current cell's value and the maximum values of the cell above it and the cell to its left. We update the dp array with these values. Finally, we return the maximum value in the dp array, which represents the optimal grid path.

Example 2

Input

N = 4, grid = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

Output

16

Explanation: Step-by-step: We initialize a 2D array dp of size (N+1) x (N+1) with all values set to 0. We iterate over the grid and for each cell, we calculate the maximum value that can be obtained by moving either right or down from the cell. The maximum value is the maximum of the current cell's value and the maximum values of the cell above it and the cell to its left. We update the dp array with these values. Finally, we return the maximum value in the dp array, which represents the optimal grid path.

Constraints

  • 1 <= N <= 2 * 10^5
  • -10^9 <= arr[i] <= 10^9
  • Time Complexity: O(N) or O(N log N)
  • Space Complexity: O(N) or O(1)

Optimal Approach & Strategy

Use dynamic programming: compute dp[i][j] = grid[i][j] + max(dp[i-1][j], dp[i][j-1]) for all cells in a single pass, storing only the current row to achieve O(N) space.

Brute Force Approach

Enumerate all possible right/down paths from the top-left to bottom-right, summing the values along each path, and return the maximum sum. This requires exploring C(2N-2, N-1) paths, leading to exponential time complexity.

Verified Code Solutions

JavaScript Solution
Time: O(N^2)
function solution(grid) {
      const N = grid.length;
      const dp = Array(N + 1).fill(0).map(() => Array(N + 1).fill(0));
      for (let i = 1; i <= N; i++) {
         for (let j = 1; j <= N; j++) {
            dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]) + grid[i - 1][j - 1];
         }
      }
      return Math.max(...dp[N]);
   }

Asked in Top Tech Interviews

CognizantPhonePe

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.