fork download
  1. import java.util.*;
  2. class Solution {
  3. public static int maxLength(int arr[]) {
  4. // code here
  5. int n=arr.length;
  6. int target=0;
  7. Map<Integer, Integer> map = new HashMap<>();
  8.  
  9. int prefixSum = 0;
  10. int maxLength = 0;
  11.  
  12. map.put(0, -1);
  13.  
  14. for (int j = 0; j < n; j++) {
  15. prefixSum += arr[j];
  16.  
  17. int x = prefixSum - target;
  18.  
  19. if (map.containsKey(x)) {
  20. int i = map.get(x);
  21. int currentLength = j - i;
  22. if (currentLength > maxLength) {
  23. maxLength = currentLength;
  24. }
  25. }
  26.  
  27. map.putIfAbsent(prefixSum, j);
  28. }
  29.  
  30. return maxLength;
  31. }
  32. public static void main(String[] args){
  33. int [] arr={15, -2, 2, -8, 1, 7, 10, 23};
  34. int ans=maxLength(arr);
  35. System.out.println("Largest subarray length with 0 sum : "+ans);
  36. }
  37. }
Success #stdin #stdout 0.12s 53680KB
stdin
Standard input is empty
stdout
Largest subarray length with 0 sum : 5