Find the length of largest subarray with 0 sum | C # program to find maximum length subarray with 0 sum ; Returns length of the maximum length subarray with 0 sum ; Creates an empty hashMap hM ; Initialize sum of elements ; Initialize result ; Traverse through the given array ; Add current element to sum ; Look this sum in hash table ; Else put this sum in hash table ; Driver code
using System ; using System . Collections . Generic ; public class MaxLenZeroSumSub { static int maxLen ( int [ ] arr ) { Dictionary < int , int > hM = new Dictionary < int , int > ( ) ; int sum = 0 ; int max_len = 0 ; for ( int i = 0 ; i < arr . GetLength ( 0 ) ; i ++ ) { sum += arr [ i ] ; if ( arr [ i ] == 0 && max_len == 0 ) max_len = 1 ; if ( sum == 0 ) max_len = i + 1 ; int prev_i = 0 ; if ( hM . ContainsKey ( sum ) ) { prev_i = hM [ sum ] ; } if ( hM . ContainsKey ( sum ) ) max_len = Math . Max ( max_len , i - prev_i ) ; else { if ( hM . ContainsKey ( sum ) ) hM . Remove ( sum ) ; hM . Add ( sum , i ) ; } } return max_len ; } public static void Main ( ) { int [ ] arr = { 15 , - 2 , 2 , - 8 , 1 , 7 , 10 , 23 } ; Console . WriteLine ( " Length ▁ of ▁ the ▁ longest ▁ 0 ▁ sum ▁ subarray ▁ is ▁ " + maxLen ( arr ) ) ; } }