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: [6, 1]
💡 Note: There is one path: S(0) → 1(1) → 2(3) → 3(6) → E. The maximum score is 6 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
Number of Paths with Max Score INPUT E 2 3 2 X 2 1 2 S End (E) Start (S) Treasure Obstacle board = ["E23", "2X2", "12S"] ALGORITHM STEPS 1 Initialize DP dp[i][j] = (maxSum, pathCount) 2 Start from S dp[2][2] = (0, 1) 3 Fill DP Table Move: up, left, diag 4 Track Max Paths Count paths with max sum DP Table (maxSum): 7 5 3 5 X 2 3 2 0 FINAL RESULT Optimal Path Found: E 2 3 2 X 2 1 2 S Path Sum Calculation: S(0) + 2 + 2 + 1 + 2 + E(0) = 7 Output: [7, 1] Key Insight: Use 2D DP where each cell stores (maxSum, pathCount). Process from Start to End. For each cell, take maximum from right, down, or diagonal neighbors. If multiple paths give same max sum, accumulate their counts. Time: O(n^2), Space: O(n^2) TutorialsPoint - Number of Paths with Max Score | Dynamic Programming Approach
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