题目

image.png

思路:滑动窗口

  • 右指针right,每轮循环往前走一步。for(int right = 0; right < len_size; ++right){}
  • 如果出现不同时符合两个条件(1.Other.特定情况股票买卖 - 图22.Other.特定情况股票买卖 - 图3)的数组,那么左边的指针需要不断往右走,直到满足条件才可以
  • 为什么滑动窗口是有效的?因为滑动窗口遍历了所有满足条件的子数组

    代码:

    ```cpp

    include

    include

    include

using namespace std;

int main() { int n, m, k; cin >> n >> m >> k;

  1. // input array
  2. vector<int> nums;
  3. for (int i = 0; i < n; ++i) {
  4. int input = 0;
  5. cin >> input;
  6. nums.push_back(input);
  7. }
  8. int cnt_nega = 0, max_comb = 0;
  9. for (int right = 0, left = 0; right < n; ++right) {
  10. int right_num = nums[right], left_num = nums[left];
  11. if (right_num < 0) {cnt_nega++;}
  12. while (left < right && right_num + left_num > k && cnt_nega > m) {
  13. if (left_num < 0) {cnt_nega--;}
  14. left++;
  15. left_num = nums[left];
  16. }
  17. if (left != right) {max_comb = max(max_comb, left_num + right_num);}
  18. }
  19. cout << "max_comb is: " << max_comb << endl;
  20. return 0;

}

```