Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

longest subarray with equal 0 and 1

private static int longestSubarrayWithEqualNumberOfZeroAndOne(int[]arr){

        // AyushG Notes
        // replace 0 with -1 int the given array and the problem will be converted to
        // longestSubarraySum problem with given sum = 0

        int currSum=0;
        int sum=0;
        int maxLen=0;
        for(int i=0; i<arr.length; i++){
            if(arr[i]==0){
                arr[i]=-1;
            }
        }
        HashMap<Integer,Integer> map = new HashMap<>();
        for(int i =0; i<arr.length; i++){
            currSum=currSum+arr[i];

            if(currSum==sum){
                maxLen=i+1;
            }
            if(!map.containsKey(currSum)){
                map.put(currSum,i);
            }
            if(map.containsKey(currSum-sum)){
                maxLen = Math.max(maxLen, i-map.get(currSum-sum));
            }
        }
        return maxLen;
    }
Comment

PREVIOUS NEXT
Code Example
Java :: primitive vs wrapper classes in java 
Java :: java test coverage 
Java :: how to remove all components from layeredPane java 
Java :: null check in line java 
Java :: Picked up _JAVA_OPTIONS: -Xmx256M intillij 
Java :: sysout is not working in eclipse 
Java :: java try-with-resources nested streams 
Java :: validate list of objects in javax validation 
Java :: SmallChange 
Java :: Java Remove Elements 
Java :: zweidimensionales array erstellen java 
Java :: output of java file in terminal 
Java :: Java Labeled continue Statement Java 
Java :: os compatible java path separator 
Java :: Java Creating a LinkedHashMap 
Java :: lcd initialize arduino 
Java :: firebase persistence enable android 
Java :: java datasource 
Java :: convert system.currenttimemillis to string kotlin 
Java :: how to come from 2nd fragment to first fragment android 
Java :: with uses in python 
Java :: bukkit shutdown 
Java :: Child inside NestedScrollView not cover full height of screen 
Java :: Write a java program to print a number from the user 
Java :: Not allowed to bind to service Intent 
Java :: time in java 
Java :: mostrar divisores java 
Java :: springboot getting body value 
Java :: replacing string with dynamic avalues java 
Java :: tree algorithm example 
ADD CONTENT
Topic
Content
Source link
Name
8+7 =