Warehouse Shelf Stacking - Problem

You are managing a warehouse where items need to be collected from shelves arranged in a grid. Each cell in the grid represents a shelf with a specific number of items that can be picked up.

Starting from the top-left corner (position [0,0]), you need to reach the bottom-right corner while collecting the maximum possible number of items. You can only move right or down at each step.

Given a 2D grid shelves where shelves[i][j] represents the number of items on shelf at position [i,j], return the maximum number of items you can collect on your path from top-left to bottom-right.

Input & Output

Example 1 — Basic 2x3 Grid
$ Input: shelves = [[1,3,1],[1,5,1]]
Output: 10
💡 Note: Path: (0,0)→(0,1)→(1,1)→(1,2) collecting 1+3+5+1 = 10 items. This is better than going (0,0)→(1,0)→(1,1)→(1,2) which gives 1+1+5+1 = 8 items.
Example 2 — Single Row
$ Input: shelves = [[1,2,3,4]]
Output: 10
💡 Note: Only one path possible: move right through all cells collecting 1+2+3+4 = 10 items.
Example 3 — Single Column
$ Input: shelves = [[1],[2],[3]]
Output: 6
💡 Note: Only one path possible: move down through all cells collecting 1+2+3 = 6 items.

Constraints

  • 1 ≤ shelves.length ≤ 200
  • 1 ≤ shelves[i].length ≤ 200
  • 0 ≤ shelves[i][j] ≤ 100

Visualization

Tap to expand
INPUT GRIDDP ALGORITHMFINAL RESULT131151Start: Top-Left (0,0)Goal: Bottom-Right (1,2)Moves: Right ↓ or Down ↓1Initialize DP table2Fill bottom row & right column3dp[i][j] = shelves[i][j] +max(dp[i+1][j], dp[i][j+1])4Return dp[0][0]10Maximum ItemsCollectedOptimal Path:1 → 3 → 5 → 1Total: 10 itemsKey Insight:Each cell's optimal value is its items plus the better choice between going right or down,eliminating the need to explore all exponential paths.TutorialsPoint - Warehouse Shelf Stacking | 2D Dynamic Programming
Asked in
Amazon 45 Google 38 Microsoft 32 Apple 28
85.0K Views
High Frequency
~15 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen