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
相关推荐
木井巳6 小时前
【BFS/DFS 解决 FloodFill 算法】太平洋大西洋水流问题
java·算法·leetcode·深度优先·广度优先·宽度优先·推荐算法
心抵鹊6 小时前
归并排序之翻转对(hard)
数据结构·算法
白山编程大哥6 小时前
Java 集合算法:从排序、查找到底层原理的实战指南
java·python·算法
shehuiyuelaiyuehao6 小时前
算法34,位运算符操作,总结
算法
Navigator_Z7 小时前
LeetCode //C - 1224. Maximum Equal Frequency
c语言·算法·leetcode
Navigator_Z7 小时前
LeetCode //C++ - 1226. The Dining Philosophers
c语言·算法·leetcode
FOORIR7 小时前
3D视觉+AI客流系统怎么做:从Sensor Pipeline到数据事件引擎
算法
我命由我123457 小时前
Photoshop - Photoshop 把两个 PSD 文件合并
学习·ui·职场和发展·产品运营·产品经理·学习方法·photoshop
Omics Pro9 小时前
Arc研究所Cell|全新虚拟细胞官方基准评测框架
大数据·人工智能·深度学习·算法·机器学习
CoderYanger11 小时前
A.每日一题:1140. 石子游戏 II
java·程序人生·算法·leetcode·游戏·职场和发展·深度优先