C# single pass O(n) space


  • 0
    H
    public int FindMaxLength(int[] nums) {
            Dictionary<int, int> firstidx = new Dictionary<int, int>();
            int max = 0, sum = 0;
            firstidx[0] = -1;
            for(int i = 0; i < nums.Length; i++) {
                sum += nums[i] == 0 ? -1 : 1;
                if (firstidx.ContainsKey(sum)) {
                    max = Math.Max(max, i - firstidx[sum]);
                } else {
                    firstidx[sum] = i;
                }
            }
            
            return max;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.