748. Column-Shift Falling Path
A maintenance robot descends a warehouse shelf grid, one row at a time, and must pick up exactly one crate from every row. grid[r][c] is the effort of lifting the crate in row r and column c. After picking a crate the robot moves down to the next row, and the crate it picks there must be in a different column from the previous pick (it may be any other column, however far away).
Return the minimum total effort of a complete descent. The grid may be rectangular. If there is a single column but more than one row, no valid descent exists and you return -1. A grid with one row simply returns its cheapest entry.
Aim for time O(rows * cols) and extra space O(1).
Example 1
- Input:
- grid = [[4,7,2],[6,3,9],[8,5,1]]
- Output:
- 6
- Explanation:
Pick 2 (column 2), 3 (column 1) and 1 (column 2): consecutive picks never share a column, total 6.
Example 2
- Input:
- grid = [[5],[9]]
- Output:
- -1
- Explanation:
One column and two rows means both picks would share the column, so the answer is -1.
Example 3
- Input:
- grid = [[3,8,3,6]]
- Output:
- 3
- Explanation:
A single row just returns its cheapest crate, 3.
Constraints
1 ≤ rows, cols ≤ 800
0 ≤ grid[r][c] ≤ 104
All rows have the same length.
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)
- Space
- O(1)