23.选数
描述:
思路:
采用滑动窗口的方式,先对数组进行排序,然后维持k范围的一个滑动窗口,如果条件满足,就返回当前窗口的最大值,如果条件不满足那就将当前的窗口向前移动一格,以此反复。
代码:
#include <bits/stdc++.h>
using namespace std;
int main() {
// int a, b;
// while (cin >> a >> b) { // 注意 while 处理多个 case
// cout << a + b << endl;
// }
int n,k;
long long s;
cin >> n >> k >> s;
vector<int> nums(n);
for(int i = 0;i<n;i++){
cin >> nums[i];
}
sort(nums.begin(), nums.end());
long long sum = nums[0];
if(sum >= s) {
cout << nums[0] << endl;
return 0;
}
int right = 1, left = 0;
while(right < n) {
if(right - left < k) {
sum += nums[right];
} else {
sum += nums[right] - nums[left++];
}
if(sum >= s) {
cout << nums[right] << endl;
return 0;
}
right++;
}
cout << -1 << endl; // 如果没有找到符合条件的子数组,返回 -1
return 0;
}