logtrick

LogTrick:++把答案按二进制位逐位判定,用贡献思想算每一位能不能为1++,常用在求子数组/子序列GCD、OR、AND计数问题里

lc3605

二分 + logtrick:

用二分猜最小稳定距离 tar ,校验时从左到右把数往前递推 GCD,超出距离就用最多 maxC 次机会把当前数强行改成 1,求能让所有数变稳定的最小 tar

class Solution {

public:

int minStable(vector<int>& nums, int maxC) {

int n = nums.size();

if(ranges::max(nums) == 1) return 0;

auto check = \&(int tar)->bool{

int left = maxC;

auto tmp = nums;

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

if(tmpi == 1) continue;

int j = i - 1;

for(;j >= 0;j--){

tmpj = gcd(tmpi,tmpj);

if(tmpj == 1) break;

}

if(j < i - tar){

if(left == 0) return false;

left--;

tmpi = 1;

}

}

return true;

};

int l = -1,r = n + 1;

while(l + 1 < r){

int m = (l + r) / 2;

(check(m) ? r : l) = m;

}

return r;

}

};

tle优化

栈+滑窗 预处理leftmin

class Solution {

public:

int minStable(vector<int>& nums, int maxC) {

int n = nums.size();

vector<int> left_min(n);

int bottom = 0, right_gcd = 0;

for (int i = 0, left = 0; i < n; i++) {

right_gcd = gcd(right_gcd, numsi);

while (left <= i && gcd(numsleft, right_gcd) == 1) {

if (bottom <= left) {

// 重新构建一个栈

// 由于 left 即将移出窗口,只需计算到 left+1

for (int j = i - 1; j > left; j--) {

numsj = gcd(numsj, numsj + 1);

}

bottom = i;

right_gcd = 0;

}

left++;

}

left_mini = left;

}

auto check = \&(int upper) -> bool {

int c = maxC;

int i = upper;

while (i < n) {

if (i - left_mini + 1 > upper) {

if (c == 0) {

return false;

}

c--;

i += upper + 1;

} else {

i++;

}

}

return true;

};

int left = -1, right = n / (maxC + 1);

while (left + 1 < right) {

int mid = left + (right - left) / 2;

(check(mid) ? right : left) = mid;

}

return right;

}

};

相关推荐
旖-旎1 小时前
LeetCode 518:零钱兑换||(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题
To_OC1 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
delishcomcn2 小时前
AI视觉识别+分切算法:电化铝缺陷检测与裁切一体化解锁
人工智能·算法
触底反弹2 小时前
深入理解大模型采样:Temperature、Top-K、Top-P 的原理与实战
人工智能·算法·面试
雪碧聊技术3 小时前
力扣 LCR 091. 粉刷房子 —— 动态规划入门详解
算法·动态规划
CV-Climber5 小时前
检索技术的实际应用
人工智能·算法
hhzz6 小时前
Tiger AI Platform平台中增加人脸识别功能
图像处理·人工智能·算法·计算机视觉·大模型
从零开始的代码生活_7 小时前
C++ 继承详解:访问控制、对象模型、菱形继承与设计取舍
开发语言·c++·后端·学习·算法
TsingtaoAI7 小时前
3D高斯泼溅技术发展及其在具身智能领域的应用综述
人工智能·算法·ai·具身智能·高斯泼溅