Maximum Number of Points with Cost - Problem
Imagine you're a treasure hunter navigating through an ancient temple with m floors and n rooms per floor. Each room contains a treasure worth points[r][c] points. Your goal is to maximize your treasure collection while following these rules:
- Must visit exactly one room per floor - you can't skip floors or visit multiple rooms on the same floor
- Moving costs energy - if you pick room
c1on floorrand roomc2on floorr+1, you lose|c1 - c2|points due to the energy spent traveling horizontally
Given an m × n matrix where points[i][j] represents the treasure value in room j on floor i, return the maximum points you can collect on your journey from the top floor to the bottom floor.
Think strategically! Sometimes it's worth picking a room with fewer points if it positions you better for the floors below.
Input & Output
example_1.py — Basic Matrix
$
Input:
points = [[1,2,3],[1,5,1],[3,1,1]]
›
Output:
9
💡 Note:
Optimal path: (0,1) → (1,1) → (2,0) = 2 + 5 + 3 - |1-1| - |1-0| = 10 - 0 - 1 = 9
example_2.py — Single Column
$
Input:
points = [[1,5],[2,3],[4,2]]
›
Output:
11
💡 Note:
Optimal path: (0,1) → (1,0) → (2,0) = 5 + 2 + 4 - |1-0| - |0-0| = 11 - 1 - 0 = 10. Wait, let's recalculate: (0,1) → (1,1) → (2,0) = 5 + 3 + 4 - 0 - 1 = 11
example_3.py — Large Penalties
$
Input:
points = [[1,2,3],[1,5,1],[3,1,1]]
›
Output:
9
💡 Note:
Even with potential high movement costs, the algorithm finds the optimal balance between high-value cells and movement penalties
Constraints
- m == points.length
- n == points[r].length
- 1 ≤ m, n ≤ 105
- 1 ≤ m × n ≤ 105
- 0 ≤ points[r][c] ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Initialize First Floor
Start by noting treasure values in each room of the first floor
2
Left Pass Strategy
For each floor, calculate the best score achievable when approaching each room from the left
3
Right Pass Strategy
Similarly, calculate the best score when approaching each room from the right
4
Optimal Choice
For each room, choose the better of the two approaches and add the room's treasure value
Key Takeaway
🎯 Key Insight: By using auxiliary left and right arrays to precompute optimal transitions, we transform an O(m×n²) problem into an O(m×n) solution, making it efficient enough for large inputs while maintaining optimal results.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code