719. Two Harvesters
Two harvesters work a field grid, where grid[r][c] is the number of crops in a cell. The first starts in the top-left cell and the second in the top-right cell (the same cell when there is a single column). At every step both machines move down one row at the same time, and each shifts its column by -1, 0 or +1 without leaving the field. They stop in the bottom row.
Each machine collects all crops from every cell it visits, including its start cell. When both machines visit the same cell in the same step, its crops are collected only once. Return the maximum total crops that can be collected.
Aim for time O(rows * cols^2) and space O(cols^2).
Example 1
- Input:
- grid = [[3,0,5,2],[1,8,0,4],[6,2,7,1],[0,9,3,5]]
- Output:
- 44
- Explanation:
The best pair of routes together gathers 44 crops, never counting a shared cell twice.
Example 2
- Input:
- grid = [[4],[7],[2]]
- Output:
- 13
- Explanation:
With one column both machines share every cell, so the total is just 4 + 7 + 2 = 13.
Constraints
1 ≤ rows ≤ 200
1 ≤ cols ≤ 40
0 ≤ grid[r][c] ≤ 100
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 2,400 msC++ 600 msJava 1,200 msJavaScript 1,200 msTypeScript 1,200 ms
Expected complexity
- Time
- O(rows * cols^2)
- Space
- O(cols^2)