Contiguous Array - Leetcode

Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.

Example 1:

Input: [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 
and 1.

Example 2:

Input: [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number 
of 0 and 1.
 
Note: The length of the given binary array will not exceed 50,000.
 
 

class Solution {
    public int findMaxLength(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, -1);
        int ans = 0;
        int balance = 0;
        for (int i = 0; i < nums.length; i++) {
            balance += nums[i] == 1 ? 1 : -1;
            if (map.containsKey(balance)) {
                ans = Math.max(ans, i - map.get(balance));
            } else {
                map.put(balance, i);
            }
        }
        return ans;
    }
}

METHOD 2:

class Solution {
    public int findMaxLength(int[] nums) {
        int i, j, sum = 0, maxSize = -1;
        for(i=0;i<nums.length;i++){
            sum = (nums[i]==0)? -1:1;
            for(j=i+1;j<nums.length;j++){
                if(nums[j]==0){
                    sum += -1;
                }
                else{
                    sum += 1;
                }
                if(sum == 0 && maxSize < j-i+1){
                    maxSize = j-i+1;
                }
            }
        }
        if(maxSize == -1)
        return 0;
        else
            return maxSize;
    }
}

Time Complexity : O(n^2)
Same as above method.
We are assuming 0 as -1 and 1 as 1 .
Taking each element and in inner for loop traversing till end of array and also calculating sum.
If sum = 0 then calculate maximum size.
But it is facing TLE(Time Limit Exceeded) error in Leetcode.


Try this on Leetcode

If any one had a suggestion or  different solution leave it as a comment

Comments

Popular posts from this blog

First Unique Character in a String

Balanced Binary Tree

Majority Element

Sequential Digits