fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. using namespace std;
  6.  
  7. typedef long long ll;
  8.  
  9. int main() {
  10. ios_base::sync_with_stdio(false);
  11. cin.tie(NULL);
  12.  
  13. ll n;
  14. if (!(cin >> n) || n <= 0) return 0;
  15.  
  16. vector<ll> b(n);
  17. for (ll i = 0; i < n; i++) {
  18. cin >> b[i];
  19. }
  20.  
  21. ll k;
  22. cin >> k;
  23.  
  24. ll maxLen = 0, sum = 0;
  25. for (ll i = 0, j = 0; j < n; j++) {
  26. sum += b[j];
  27.  
  28. // Ensure window stays valid and sum is <= k
  29. while (i <= j && sum > k) {
  30. sum -= b[i];
  31. i++;
  32. }
  33.  
  34. if (sum <= k) {
  35. maxLen = max(maxLen, j - i + 1);
  36. }
  37. }
  38.  
  39. cout << maxLen << "\n";
  40. return 0;
  41. }
Success #stdin #stdout 0s 5316KB
stdin
5
1 2 3 4 5
10
stdout
4