Quick actions

cmd+k|ctrl+k

Navigation

Languages

findMaxOccurence

Snippet info

Language

JavaScript

Visibility

public

Author

soham57

Created

2022-10-05T10:00:02.06456Z

Updated

2022-10-05T10:00:02.06456Z

function findMaxOccurence(array){
    let count=0, candidate=null;
    
    for(let x of array){
        
        if(count===0){
            candidate=x;
            count++;
        }
        
        else{
            if(candidate===x){
                count++;
            }
            else{
                count--
            }
        }
        
    }
    
    count=0;
    
    for(let x of array){
        if(x===candidate){
            count++;
        }
    }
    
    if(count>Math.floor(array.length/2)){
        return candidate
    }
    
    else{
        return -1
    }
}


console.log(findMaxOccurence([0,0,1,1,0,0,5]));
INFO