1698. Bounded Leap Grid Route
A frog crosses a pond laid out as the matrix grid, where grid[r][c] is the score of the lily pad at row r, column c (scores may be negative). It starts on the pad at the top-left corner and must finish on the pad at the bottom-right corner. One leap moves it right by 1 to k columns, or down by 1 to k rows, staying in the same row or column. The frog collects the score of every pad it lands on, including the start and the finish. Return the maximum total score as a long. Trying every leap length is too slow; keep a sliding-window maximum deque per row and per column to run in O(m * n) time.
Example 1
- Input:
- grid = [[1,2],[3,4]], k = 1
- Output:
- 8
- Explanation:
With single-step moves the best route is down then right: 1 + 3 + 4 = 8 (right then down gives only 7).
Example 2
- Input:
- grid = [[1,-5,2,9]], k = 3
- Output:
- 12
- Explanation:
On one row the route may skip cells: start 1, jump two columns to land on 2, then one more to the 9: 1 + 2 + 9 = 12 (jumping straight from column 0 to column 3 gives only 10).
Example 3
- Input:
- grid = [[7]], k = 1
- Output:
- 7
- Explanation:
The start and the finish are the same cell, so the total is just 7.
Constraints
1 ≤ m, n and m * n ≤ 2 * 105
1 ≤ k ≤ max(m, n)
-104 ≤ grid[i][j] ≤ 104
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(m * n)
- Space
- O(m * n)