fork download
  1. import java.util.*;
  2.  
  3. public class Main {
  4. public static int findMaxSubarrayLength(int[] arr) {
  5. Map<Integer, Integer> prefixMap = new HashMap<>();
  6. int sum = 0, maxLength = 0;
  7. prefixMap.put(0, -1);
  8.  
  9. for (int i = 0; i < arr.length; i++) {
  10. sum += arr[i];
  11.  
  12. if (prefixMap.containsKey(sum)) {
  13. maxLength = Math.max(maxLength, i - prefixMap.get(sum));
  14. } else {
  15. prefixMap.put(sum, i);
  16. }
  17. }
  18.  
  19. return maxLength;
  20. }
  21.  
  22. public static void main(String[] args) {
  23. int[] arr = {15, -2, 2, -8, 1, 7, 10, 23};
  24. System.out.println("Answer is " + findMaxSubarrayLength(arr));
  25. }
  26. }
  27.  
Success #stdin #stdout 0.14s 55532KB
stdin
Standard input is empty
stdout
Answer is 5