应该是牛客的一道题😥
思路是排序后使用滑动窗口
#include<vector> #include<iostream> #include<algorithm> #include<numeric> #include<queue> using namespace std; vector<vector<int>> re; int main() { int n,k; cin >> n;cin >> k; for (int i = 0; i < n; i++) { int x, y; vector<int> temp; cin >> x;cin >> y; temp.push_back(x); temp.push_back(y); re.push_back(temp); } if (n == 1) { return re[0][1]; } sort(re.begin(), re.end(), [](vector<int> p1,vector<int> p2) { return p1[0] < p2[0]; }); for (auto& ele : re) { cout << ele[0] <<" "<< ele[1] << endl; } string jilu = "5 3 1 3 2 1 5 2 3 1 4 3"; //使用滑动窗口收集最大值 int i = 0; int j = 0; int maxvalue=0; int sum = 0; while (j < re.size()) { if ((re[j][0] - re[i][0])<k) { sum += re[j][1]; ++j; } else { if (sum > maxvalue) maxvalue = sum; sum -= re[i][1];//加i之前要去掉i原来指向的值 ++i; } } if (j == re.size() || (re[j][0] - re[i][0]) < k) //注意如果是因为越界退出要防止少收集一段 { if (sum > maxvalue) maxvalue = sum; } return maxvalue;
}