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 f[i][j] be the sum of the submatrix from (0,0) to (i,j), and count all positions where f[i][j] ≤ 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
相关推荐
田梓燊1 小时前
力扣:23.合并 K 个升序链表
算法·leetcode·链表
re林檎2 小时前
算法札记——4.27
算法
数据牧羊人的成长笔记2 小时前
逻辑回归与Softmax回归
算法·回归·逻辑回归
郑州光合科技余经理3 小时前
同城O2O海外版二次开发实战:从支付网关到配送算法
开发语言·前端·后端·算法·架构·uni-app·php
d111111111d6 小时前
STM32-UART封装问题解析
笔记·stm32·单片机·嵌入式硬件·学习·算法
Jiangxl~7 小时前
IP数据云如何为不同行业提供精准IP查询与风险防控解决方案?
网络·网络协议·tcp/ip·算法·ai·ip·安全架构
李伟_Li慢慢7 小时前
wolfram详解山峦算法
前端·算法
counting money8 小时前
prim算法最小生成树(java)
算法
澈2078 小时前
C++面向对象:类与对象核心解析
c++·算法
用户690673881928 小时前
基于无人机的单目测距系统,平均误差仅2.12%
算法