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[] arr = {15, -2, 2, -8, 1, 7, 10};
  14. System.out.println("longest subarray with sum zero is " + longestSubarrayWithSumZero(arr));
  15. }
  16. static int longestSubarrayWithSumZero(int[] arr){
  17. HashMap<Integer,Integer> map = new HashMap<>();
  18. map.put(0,-1);
  19. int prefixSum = 0;
  20. int max = 0;
  21. for(int i=0;i<arr.length;i++){
  22. prefixSum +=arr[i];
  23. if(map.containsKey(prefixSum)){
  24. int leftIndex = map.get(prefixSum);
  25. max = Math.max(max, i-leftIndex);
  26. } else
  27. map.put(prefixSum,i);
  28. }
  29. return max;
  30.  
  31. }
  32. }
Success #stdin #stdout 0.13s 53528KB
stdin
Standard input is empty
stdout
longest subarray with sum zero is 5