LeetCode 题解工作台
使每一列严格递增的最少操作次数
给你一个由 非负 整数组成的 m x n 矩阵 grid 。 在一次操作中,你可以将任意元素 grid[i][j] 的值增加 1。 返回使 grid 的所有列 严格递增 所需的 最少 操作次数。 示例 1: 输入: grid = [[3,2],[1,3],[3,4],[0,1]] 输出: 15 解释…
3
题型
5
代码语言
3
相关题
当前训练重点
简单 · 贪心·invariant
答案摘要
我们可以逐列遍历矩阵,对于每一列,我们可以计算出使其严格递增所需的最少操作次数。具体地,对于每一列,我们可以维护一个变量 ,表示当前列中前一个元素的值。然后,我们从上到下遍历当前列,对于当前元素 ,如果 $\textit{pre} < \textit{cur}$,则说明当前元素已经大于前一个元素,我们只需要更新 $\textit{pre} = \textit{cur}$;否则,我们需要将当前元素增…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你一个由 非负 整数组成的 m x n 矩阵 grid。
在一次操作中,你可以将任意元素 grid[i][j] 的值增加 1。
返回使 grid 的所有列 严格递增 所需的 最少 操作次数。
示例 1:
输入: grid = [[3,2],[1,3],[3,4],[0,1]]
输出: 15
解释:
- 为了让第
0列严格递增,可以对grid[1][0]执行 3 次操作,对grid[2][0]执行 2 次操作,对grid[3][0]执行 6 次操作。 - 为了让第
1列严格递增,可以对grid[3][1]执行 4 次操作。

示例 2:
输入: grid = [[3,2,1],[2,1,0],[1,2,3]]
输出: 12
解释:
- 为了让第
0列严格递增,可以对grid[1][0]执行 2 次操作,对grid[2][0]执行 4 次操作。 - 为了让第
1列严格递增,可以对grid[1][1]执行 2 次操作,对grid[2][1]执行 2 次操作。 - 为了让第
2列严格递增,可以对grid[1][2]执行 2 次操作。

提示:
m == grid.lengthn == grid[i].length1 <= m, n <= 500 <= grid[i][j] < 2500
解题思路
方法一:逐列计算
我们可以逐列遍历矩阵,对于每一列,我们可以计算出使其严格递增所需的最少操作次数。具体地,对于每一列,我们可以维护一个变量 ,表示当前列中前一个元素的值。然后,我们从上到下遍历当前列,对于当前元素 ,如果 ,则说明当前元素已经大于前一个元素,我们只需要更新 ;否则,我们需要将当前元素增加到 ,并将增加的次数累加到答案中。
时间复杂度 ,其中 和 分别是矩阵 的行数和列数。空间复杂度 。
class Solution:
def minimumOperations(self, grid: List[List[int]]) -> int:
ans = 0
for col in zip(*grid):
pre = -1
for cur in col:
if pre < cur:
pre = cur
else:
pre += 1
ans += pre - cur
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(m * n) since each cell is visited once per column. Space complexity is O(1) beyond input storage, as only running totals are maintained. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate identifies a per-column approach and avoids unnecessary row comparisons across columns.
- question_mark
They correctly implement minimal increments instead of blindly adding arbitrary values.
- question_mark
They justify why processing top-down ensures the greedy invariant holds for all subsequent rows.
常见陷阱
外企场景- error
Incrementing cells without checking the previous row can violate the strictly increasing requirement.
- error
Attempting to modify rows simultaneously may overcount operations.
- error
Neglecting edge cases where multiple rows have equal values leads to incorrect totals.
进阶变体
外企场景- arrow_right_alt
Allowing decrements as well as increments to achieve strictly increasing columns.
- arrow_right_alt
Finding minimum operations for strictly increasing rows instead of columns.
- arrow_right_alt
Handling larger matrices with m, n up to 10^3, requiring optimized traversal.