当前位置:网站首页>Buckle exercise - rectangular area does not exceed the maximum value of K and (hard)
Buckle exercise - rectangular area does not exceed the maximum value of K and (hard)
2022-08-10 11:33:00 【qq_43403657】
矩形区域不超过 K 的最大数值和
1.问题描述
给定一个非空二维矩阵 matrix 和一个整数 k,找到这个矩阵内部不大于 k 的最大矩形和.
示例:
输入: matrix = [[1,0,1],[0,-2,3]], k = 2
输出: 2
解释: 矩形区域 [[0, 1], [-2, 3]] 的数值和是 2,且 2 是不超过 k 的最大数字(k = 2).
说明:
矩阵内的矩形区域面积必须大于 0.
如果行数远大于列数,你将如何解答呢?
[OJThere is an example in 1300行 13列 ,注意超时]
2.输入说明
首先输入matrix的行数m、列数n,
然后输入m行,每行n个整数.
最后输入一个整数k.
3.输出说明
输出一个整数.
4.范例
输入
2 3
1 0 1
0 -2 3
2
输出
2
5.代码
#include <iostream>
#include <queue>
#include <cstdlib>
#include <cstring>
#include<algorithm>
#include<set>
using namespace std;
int findMaxSum(vector<vector<int> >matrix, int k)
{
//思想参考:https://leetcode.cn/problems/max-sum-of-rectangle-no-larger-than-k/solution/gong-shui-san-xie-you-hua-mei-ju-de-ji-b-dh8s/
if (matrix.empty() || matrix[0].empty()) return 0;//Judgment of special circumstances
int m = matrix.size();//行
int n = matrix[0].size();//列
int res = INT_MIN;
int sum[m][n];//这里使用vectorSome samples will time out
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int t = matrix[i][j];
if (i > 0) t += sum[i - 1][j];
if (j > 0) t += sum[i][j - 1];
if (i > 0 && j > 0) t -= sum[i - 1][j - 1];
sum[i][j] = t;
for (int r = 0; r <= i; ++r) {
for (int c = 0; c <= j; ++c) {
int d = sum[i][j];
if (r > 0) d -= sum[r - 1][j];
if (c > 0) d -= sum[i][c - 1];
if (r > 0 && c > 0) d += sum[r - 1][c - 1];
if (d <= k) res = max(res, d);
}
}
}
}
return res;
}
int main()
{
vector<vector<int> > nums;
int m,n,k,tmp;
cin >> m >>n;
for (int i = 0; i < m; i++)
{
vector<int> t;
t.clear();
for (int j = 0; j < n; j++)
{
cin >> tmp;
t.push_back(tmp);
}
nums.push_back(t);
}
cin >> k;
int res = findMaxSum(nums, k);
cout << res << endl;
return 0;
}
边栏推荐
猜你喜欢
第3章-线性方程组(3)
Some tips for using Unsafe
模块九 - 设计电商秒杀系统
什么是抽象类
OneFlow source code parsing: operator instructions executed in a virtual machine
Store limited time seckill function system
Several small projects that I have open sourced over the years
基于UiAutomator2+PageObject模式开展APP自动化测试实战
Research on motion capture system for indoor combined positioning technology
【勇敢饭饭,不怕刷题之链表】链表中有环的问题
随机推荐
POJ 3101 Astronomy (数学)
POJ 1026 Cipher (Permutation Groups)
【机器学习】浅谈正规方程法&梯度下降
中小规模网站架构
LeetCode_443_压缩字符串
POJ 2891 Strange Way to Express Integers (Extended Euclidean)
杭电多校-Loop-(不确定性贪心+线段树)
3款不同类型的自媒体免费工具,有效提高创作、运营效率
力扣练习——60 二叉搜索子树的最大键值和
不止跑路,拯救误操作rm -rf /*的小伙儿
【勇敢饭饭,不怕刷题之链表】有序链表的合并
Kyligence 通过 SOC 2 Type II 审计,以可信赖的企业级产品服务全球客户
LeetCode_628_三个数的最大乘积
VSCode remote connection server error: Could not establish connection to "xxxxxx" possible error reasons and solutions
做自媒体月入几万?博主们都在用的几个自媒体工具
[Brave food, not afraid to write the linked list] The problem of the penultimate node of the linked list
Some tips for using Unsafe
Store limited time seckill function system
Introduction to Software Architecture
今天面了个腾讯拿38K出来的大佬,让我见识到了基础的天花板