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. // your code goes here
  13. Scanner sc=new Scanner (System.in);
  14. int n=sc.nextInt();
  15. int arr[]=new int[n];
  16. for(int i=0;i<n;i++){
  17. arr[i]=sc.nextInt();
  18. }
  19. System.out.println("Enter k value");
  20. int k=sc.nextInt();
  21. Ans(arr,k);
  22. }
  23. public static void Ans(int arr[],int k){
  24. int n=arr.length;
  25. int left=0;
  26. int right=0;
  27. int sum=0;
  28. int ans=0;
  29. for(right=0;right<n;right++){
  30. sum=sum+arr[right];
  31. while(sum>k){
  32. sum=sum-arr[left];
  33. left++;
  34. }
  35. ans=ans+(right-left+1);
  36.  
  37. }
  38. System.out.println(ans);
  39. }
  40. }
Success #stdin #stdout 0.1s 38940KB
stdin
5
2
1
1
5
6
4
stdout
Enter k value
6