fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. Scanner s = new Scanner(System.in);
  13.  
  14. // Input size of the array
  15. int N = s.nextInt();
  16. int[] a = new int[N];
  17.  
  18. // Input array elements
  19. for (int i = 0; i < N; i++) {
  20. a[i] = s.nextInt();
  21. }
  22.  
  23. // Input the value of k
  24. int k = s.nextInt();
  25.  
  26. // Sliding window logic
  27. int si = 0, sum = 0, maxlen = 0;
  28. for(int ei=0;ei<N;ei++) {
  29. sum += a[ei]; // Expand the window
  30.  
  31. // Shrink the window while the sum exceeds k
  32. while (sum > k) {
  33. sum -= a[si];
  34. si++;
  35. }
  36.  
  37. // Update maxlen if the current window satisfies the condition
  38. maxlen = Math.max(maxlen, (ei - si) + 1);
  39.  
  40. }
  41.  
  42. // Output the result
  43. System.out.println(maxlen);
  44.  
  45. s.close();
  46. }
  47. }
  48.  
Success #stdin #stdout 0.12s 56628KB
stdin
7
4 3 -2 1 6 8 2
7
stdout
4