Number of Paths with Max Score - Problem
Number of Paths with Max Score

Imagine you're navigating a treasure-filled dungeon represented as a square grid! You start at the bottom-right corner marked with 'S' and need to reach the top-left corner marked with 'E'.

Each cell contains either:
• A treasure value (digits 1-9) that you can collect
• An obstacle marked with 'X' that blocks your path

You can move in three directions: up, left, or diagonally up-left. Your goal is to find the path that maximizes your treasure collection!

Return: A list with two integers:
1. The maximum sum of treasure you can collect
2. The number of different paths that achieve this maximum sum (modulo 109 + 7)

If no path exists, return [0, 0].

Input & Output

example_1.py — Basic Path Finding
$ Input: board = ["E23", "2X2", "12S"]
Output: [7, 1]
💡 Note: There is one path: S(0) → 1(1) → 2(3) → 2(5) → 3(8) → E. The maximum score is 7 and there's exactly 1 path achieving this score.
example_2.py — Multiple Optimal Paths
$ Input: board = ["E12", "1X1", "21S"]
Output: [4, 2]
💡 Note: There are two optimal paths: S(0) → 1(1) → 2(3) → 1(4) → E and S(0) → 2(2) → 1(3) → 1(4) → E. Both achieve maximum score of 4.
example_3.py — No Valid Path
$ Input: board = ["E11", "XXX", "11S"]
Output: [0, 0]
💡 Note: All paths from S to E are blocked by obstacles 'X', so there's no valid path. Return [0, 0].

Constraints

  • 2 ≤ board.length == board[i].length ≤ 100
  • board[i][j] is one of 'E', 'S', '1', '2', ..., '9', or 'X'
  • It is guaranteed that board[0][0] == 'E' and board[n-1][n-1] == 'S'
  • Answer fits in 32-bit signed integer

Visualization

Tap to expand
EScore: 0Paths: 13Score: 3Paths: 15Score: 8Paths: 12Score: 2Paths: 1XBLOCKED1Score: 6Paths: 14Score: 6Paths: 16Score: 12Paths: 1SScore: 16Paths: 1🏴‍☠️ Optimal Treasure RoutePath: S(0) → 6(6) → 4(10) → 2(12) → ETotal Treasure: 16 coinsNumber of optimal paths: 1💡 DP builds solution backwards:Each room knows the best future treasure!
Understanding the Visualization
1
Set Base Camp
Mark the destination 'E' with score (0, 1) - no treasure needed here, one way to 'finish'
2
Map Adjacent Rooms
Calculate treasure scores for cells next to destination, considering all three possible approaches
3
Build Treasure Map
Continue row by row, each cell learns the optimal treasure and path count from future positions
4
Find Starting Strategy
The starting position 'S' now contains the maximum treasure and total optimal paths
Key Takeaway
🎯 Key Insight: Dynamic Programming transforms this exponential search into an efficient O(n²) solution by building optimal substructure from destination to source, avoiding redundant path explorations.
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 25
48.2K Views
Medium-High Frequency
~25 min Avg. Time
1.9K 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