|
| 1 | +/* |
| 2 | +Given an array consisting of positive and negative integers, find the length of the longest subarray whose sum is zero. |
| 3 | + |
| 4 | +Input Format: |
| 5 | +The first line of input contains an integer, that denotes the value of the size of the array. Let us denote it with the symbol N. |
| 6 | +The following line contains N space separated integers, that denote the value of the elements of the array. |
| 7 | + |
| 8 | +Output Format |
| 9 | +The first and only line of output contains length of the longest subarray whose sum is zero. |
| 10 | + |
| 11 | +Constraints: |
| 12 | +0 <= N <= 10^8 |
| 13 | +Time Limit: 1 sec |
| 14 | + |
| 15 | +Sample Input 1: |
| 16 | +10 |
| 17 | + 95 -97 -387 -435 -5 -70 897 127 23 284 |
| 18 | +Sample Output 1: |
| 19 | +5 |
| 20 | +Explanation: |
| 21 | +The five elements that form the longest subarray that sum up to zero are: -387, -435, -5, -70, 897 |
| 22 | +*/ |
| 23 | +import java.util.HashMap; |
| 24 | +public class Solution { |
| 25 | + |
| 26 | + public static int lengthOfLongestSubsetWithZeroSum(int arr[]) { |
| 27 | + // Write your code here |
| 28 | + HashMap<Integer,Integer> map = new HashMap<>(); |
| 29 | + int sum=0,maxLen=-1; |
| 30 | + for (int i=0;i<arr.length;i++) |
| 31 | + { |
| 32 | + sum=sum+arr[i]; |
| 33 | + //System.out.println("Current cumulative sum: "+sum); |
| 34 | + if (sum==0) |
| 35 | + { |
| 36 | + maxLen=i+1; |
| 37 | + } |
| 38 | + if (map.containsKey(sum)) |
| 39 | + { |
| 40 | + int prevIndex=map.get(sum); |
| 41 | + //System.out.println("Sum found previously at index: "+prevIndex); |
| 42 | + int currLen=i-prevIndex; |
| 43 | + //System.out.println("Length of 0 sum: "+currLen); |
| 44 | + if (currLen>maxLen) |
| 45 | + { |
| 46 | + maxLen=currLen; |
| 47 | + //System.out.println("Max Length of 0 sum: "+maxLen); |
| 48 | + } |
| 49 | + } |
| 50 | + else |
| 51 | + { |
| 52 | + //System.out.println("Adding sum to HashMap"); |
| 53 | + map.put(sum,i); |
| 54 | + } |
| 55 | + //System.out.println(); |
| 56 | + } |
| 57 | + return maxLen; |
| 58 | + } |
| 59 | +} |
0 commit comments