1.713. 乘积小于 K 的子数组
class Solution {
public:
int numSubarrayProductLessThanK(vector<int>& nums, int k) {
if (k == 0) {
return 0;
}
int n = nums.size();
vector<double> logPrefix(n + 1);
for (int i = 0; i < n; i++) {
logPrefix[i + 1] = logPrefix[i] + log(nums[i]);
}
double logk = log(k);
int ret = 0;
for (int j = 0; j < n; j++) {
int l = upper_bound(logPrefix.begin(), logPrefix.begin() + j + 1, logPrefix[j + 1] - log(k) + 1e-10) - logPrefix.begin();
ret += j + 1 - l;
}
return ret;
}
};
2.2024. 考试的最大困扰度
class Solution {
public:
int maxConsecutiveChar(string& answerKey, int k, char ch) {
int n = answerKey.length();
int ans = 0;
for (int left = 0, right = 0, sum = 0; right < n; right++) {
sum += answerKey[right] != ch;
while (sum > k) {
sum -= answerKey[left++] != ch;
}
ans = max(ans, right - left + 1);
}
return ans;
}
int maxConsecutiveAnswers(string answerKey, int k) {
return max(maxConsecutiveChar(answerKey, k, 'T'),
maxConsecutiveChar(answerKey, k, 'F'));
}
};
3.1984. 学生分数的最小差值
class Solution {
public:
int minimumDifference(vector<int>& nums, int k) {
int n = nums.size();
sort(nums.begin(), nums.end());
int ans = INT_MAX;
for (int i = 0; i + k - 1 < n; ++i) {
ans = min(ans, nums[i + k - 1] - nums[i]);
}
return ans;
}
};