fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int longestSubarray(vector<int>& arr, int k){
  5. int n = arr.size();
  6. int length = 0, sum = 0;
  7.  
  8. for (int i = 0, j = 0; j < n; j++){
  9. sum += arr[j];
  10.  
  11. while(sum > k){
  12. sum -= arr[i];
  13. i++;
  14. }
  15.  
  16. length = max(length, (j-i+1));
  17. }
  18.  
  19. return length;
  20. }
  21.  
  22. int main() {
  23. // your code goes here
  24.  
  25. vector<int> arr = {8, 2, 4, 7, 1};
  26. cout << longestSubarray(arr, 15);
  27. return 0;
  28. }
Success #stdin #stdout 0.01s 5292KB
stdin
Standard input is empty
stdout
4