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. int n = 4;
  14. int k = 4;
  15. int[] arr = new int[]{1,3,2,4};
  16.  
  17. System.out.println(helper(arr,n,k));
  18. }
  19. static int helper(int[]arr, int n, int k){
  20. int[] preSum = new int[n];
  21. HashMap<Integer,Integer> map = new HashMap<>();
  22. int cnt = 0;
  23. preSum[0] = arr[0];
  24. for(int i=1;i<n;i++){
  25. preSum[i] = preSum[i-1]+arr[i];
  26. }
  27. map.put(0,1);
  28. for(int i=0;i<n;i++){
  29. int modFreq = (preSum[i]%k-i%k+k)%k;
  30. cnt+= map.getOrDefault(modFreq,0);
  31. map.put(modFreq,map.getOrDefault(modFreq,0)+1);
  32. }
  33.  
  34. return cnt;
  35. }
  36. }
Success #stdin #stdout 0.07s 54564KB
stdin
Standard input is empty
stdout
2