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. // Example input
  13. int[] arr = {1, -1, 5, -2, 3};
  14. int k = 3;
  15.  
  16. Map<Long, Integer> map = new HashMap<>();
  17.  
  18. long sum = 0;
  19. int maxLen = 0;
  20.  
  21. for (int i = 0; i < arr.length; i++) {
  22. sum += arr[i];
  23.  
  24. // If prefix sum itself equals k
  25. if (sum == k) {
  26. maxLen = i + 1;
  27. }
  28.  
  29. // If (sum - k) seen before
  30. if (map.containsKey(sum - k)) {
  31. maxLen = Math.max(maxLen, i - map.get(sum - k));
  32. }
  33.  
  34. // Store first occurrence only
  35. if (!map.containsKey(sum)) {
  36. map.put(sum, i);
  37. }
  38. }
  39.  
  40. System.out.println("Largest Subarray Length: " + 1);
  41. }
  42. }
Success #stdin #stdout 0.12s 52520KB
stdin
Standard input is empty
stdout
Largest Subarray Length: 1