正反两次扫描|单调性cut

lc3047

遍历所有矩形对,计算每对矩形的交集区域,取++交集的宽高min++作为可能的正方形边长,记录最大边长并返回其平方值。

class Solution {

public:

long long largestSquareArea(vector<vector<int>>& bottomLeft, vector<vector<int>>& topRight) {

int max_side = 0;

for (int i = 0; i < bottomLeft.size(); i++) {

auto& b1 = bottomLeft[i];

auto& t1 = topRight[i];

for (int j = 0; j < i; j++) {

auto& b2 = bottomLeft[j];

auto& t2 = topRight[j];

int width = min(t1[0], t2[0]) - max(b1[0], b2[0]);

int height = min(t1[1], t2[1]) - max(b1[1], b2[1]);

++int side = min(width, height);
max_side = max(max_side, side);
++

}

}

return 1LL * max_side * max_side;

}

};

单调性cut

class Solution {

public:

long long largestSquareArea(vector<vector<int>>& bottomLeft, vector<vector<int>>& topRight) {

int max_side = 0;

for (int i = 0; i < bottomLeft.size(); i++) {

auto& b1 = bottomLeft[i];

auto& t1 = topRight[i];

++if (t1[0] - b1[0] <= max_side || t1[1] - b1[1] <= max_side)
continue;
++ // 最优性剪枝:max_side 不可能变大

for (int j = 0; j < i; j++) {

auto& b2 = bottomLeft[j];

auto& t2 = topRight[j];

int width = min(t1[0], t2[0]) - max(b1[0], b2[0]); // 右上横坐标 - 左下横坐标

int height = min(t1[1], t2[1]) - max(b1[1], b2[1]); // 右上纵坐标 - 左下纵坐标

int side = min(width, height);

max_side = max(max_side, side);

}

}

return 1LL * max_side * max_side;

}

};

lc3796

正反两次扫描

class Solution {

public:

int findMaxVal(int n, vector<vector<int>>& restrictions, vector<int>& diff) {

vector<int> max_val(n, INT_MAX);

for (auto& r : restrictions)

max_val[r[0]] = r[1];

vector<int> a(n);

for (int i = 0; i < n - 1; i++) {

a[i + 1] = min(a[i] + diff[i], max_val[i + 1]);

}

for (int i = n - 2; i > 0; i--) {

a[i] = min(a[i], a[i + 1] + diff[i]);

}

return ranges::max(a);

}

};

lc3795

hash+滑窗

class Solution {

public:

int minLength(vector<int>& nums, int k) {

unordered_map<int, int> cnt;

int sum = 0;

int left = 0;

int ans = INT_MAX;

for (int i = 0; i < nums.size(); i++) {

// 1. 入

int x = nums[i];

cnt[x]++;

if (cnt[x] == 1)

sum += x;

while (sum >= k) {

// 2. 更新答案

ans = min(ans, i - left + 1);

// 3. 出

int out = nums[left];

cnt[out]--;

if (cnt[out] == 0)

sum -= out;

left++;

}

}

return ans == INT_MAX ? -1 : ans;

}

};

相关推荐
Yzzz-F2 小时前
牛客小白月赛127 E
算法
大锦终2 小时前
递归回溯综合练习
c++·算法·深度优先
Keep__Fighting2 小时前
【神经网络的训练策略选取】
人工智能·深度学习·神经网络·算法
晚风吹长发2 小时前
初步了解Linux中的动静态库及其制作和使用
linux·运维·服务器·数据结构·c++·后端·算法
sin_hielo2 小时前
leetcode 3453(二分法)
算法
风之歌曲3 小时前
c++高精度模板
c++·算法·矩阵
嵌入式进阶行者3 小时前
【算法】深度优先搜索实例:华为OD机考双机位A卷- 中庸行者
c++·算法·华为od·深度优先
a3535413823 小时前
参数化曲线弧长公式推导
算法
不知名XL4 小时前
day27 贪心算法 part05
算法·贪心算法