fork download
  1. /******************************************************************************
  2.  
  3.   Online Java Compiler.
  4.   Code, Compile, Run and Debug java program online.
  5. Write your code in this editor and press "Run" button to execute it.
  6.  
  7. *******************************************************************************/
  8. import java.util.*;
  9. public class Main
  10. {
  11. public static void main(String[] args) {
  12. int [] arr={1,2,3,4,5};
  13. int k=5;
  14. HashMap<Integer,Integer>map=new HashMap<>();
  15. map.put(0,-1);
  16. int sum=0;
  17. int maxlen=0;
  18. for(int i=0;i<arr.length;i++){
  19. sum+=arr[i];
  20. if(map.containsKey(sum-k)){
  21.  
  22.  
  23. maxlen=Math.max(maxlen,i-map.get(sum-k));
  24. }
  25. map.putIfAbsent(sum,i);
  26. }
  27.  
  28. int prefix[]=new int[arr.length+1];
  29. int count1=0;
  30. for(int i=1;i<=arr.length;i++){
  31. prefix[i]=prefix[i-1]+arr[i-1];
  32.  
  33. }
  34. for(int i=0;i+maxlen<=arr.length;i++){
  35. int currentsum=prefix[i+maxlen]-prefix[i];
  36. if(currentsum==k){
  37. count1++;
  38. }
  39. }
  40. System.out.println(count1);
  41.  
  42. }
  43. }
Success #stdin #stdout 0.07s 52472KB
stdin
Standard input is empty
stdout
1