Advertisement
informaticage

Variable Length Sliding Window

Mar 5th, 2023
617
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.91 KB | None | 0 0
  1. /**
  2.  * Title: Variable Length Sliding window
  3.  * Author: Samuel Finocchio
  4.  * Date: 05/03/2023
  5.  *
  6.  */
  7.  
  8. #include <iostream>
  9. #include <vector>
  10. #include <limits>
  11.  
  12. int main() {
  13.   int N, C;
  14.   std::cin >> N >> C;
  15.  
  16.   std::vector<int> numbers;
  17.   numbers.reserve(N);
  18.  
  19.   for (int i = 0; i < N; i++) {
  20.     int temp;
  21.     std::cin >> temp;
  22.  
  23.     numbers.push_back(temp);
  24.   }
  25.  
  26.   int optimal = std::numeric_limits<int>::max();
  27.  
  28.   int start = 0, end = 0, sum = numbers.at(0);
  29.   while (start < numbers.size()) {
  30.     if (sum >= C) {
  31.       optimal = std::min(optimal, (end - start) + 1);
  32.       // Removing from left side
  33.       sum = sum - (numbers.at(start));
  34.       start++;
  35.     } else {
  36.       // Adding to the right side
  37.       end++;
  38.  
  39.       if (end < numbers.size()) {
  40.         sum = sum + (numbers.at(end));
  41.       } else {
  42.         break;
  43.       }
  44.     }
  45.   }
  46.  
  47.   std::cout << optimal;
  48.   return 0;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement