Leetcode 3070. Count Submatrices with Top-Left Element and Sum Less Than k

Problem

You are given a 0-indexed integer matrix grid and an integer k.

Return the number of submatrices that contain the top-left element of the grid, and have a sum less than or equal to k.

Algorithm

Dynamic programming (DP): let fij be the sum of the submatrix from (0,0) to (i,j), and count all positions where fij ≤ k.

Code

python3 复制代码
class Solution:
    def countSubmatrices(self, grid: List[List[int]], k: int) -> int:
        m, n, ans = len(grid), len(grid[0]), 0
        for i in range(m):
            for j in range(n):
                if i > 0:
                    grid[i][j] += grid[i-1][j]
                if j > 0:
                    grid[i][j] += grid[i][j-1]
                if i > 0 and j > 0:
                    grid[i][j] -= grid[i-1][j-1]
                if grid[i][j] <= k:
                    ans += 1
        
        return ans
相关推荐
考研保研资料分享8 分钟前
2022编辑出版跨保西北大学中国史:五校面试与九月补材料
面试·职场和发展
Data analyse4561 小时前
rnweb 回放数据量太大怎么办?分片存储与断点续传的实现思路
前端·网络·算法·数据分析
员工风险管理实务1 小时前
职务侵占有什么价值?岗位关联性与必要性判断
职场和发展
Navigator_Z2 小时前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil2083 小时前
leetcode 64最小路径和
算法·leetcode·职场和发展
光影少年3 小时前
AI Agent、自动化与未来工作
人工智能·算法·架构
牧羊人.3333 小时前
计算机视觉基础 第16章|EigenFace,FisherFace,LBPH传统人脸识别算法
人工智能·算法·计算机视觉
考研保研资料分享3 小时前
双非新闻学保研复盘:东华小组展示、长安面试与兰大预推免
面试·职场和发展
Nil2083 小时前
leetcode 72编辑距离
算法·leetcode·职场和发展
神工坊3 小时前
技术分享︱SIMFORGE HSF® 网格加密与热点加速技术实践
算法·hpc·网格·cae·工程仿真·数值引擎·samr