Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,907 questions

51,839 answers

573 users

How to find the maximum distance between two occurrences of same number in array with Node.js

1 Answer

0 votes
function GetMaxDistance(arr) {
    let map = new Map();
    let maximumDistance = 0;
    const size = arr.length;
    
    for (let i = 0; i < size; i++) {
        if (!map.has(arr[i])) {
            map.set(arr[i],i);
            console.log("map[arr[i]]=" + map.get(arr[i]) + " arr[i]=" + arr[i] + " i=" + i);
        }
        else {
            maximumDistance = Math.max(maximumDistance, i - map.get(arr[i]));
            console.log("map[arr[i]]=" + map.get(arr[i]) + " i - map[arr[i]]=" + (i - map.get(arr[i])) + " i=" + i);
        }
    }
    return maximumDistance;
}

const arr = [1, 7, 1, 4, 3, 1, 5, 3, 4, 9, 1, 3];

console.log(GetMaxDistance(arr));




/*
run:

map[arr[i]]=0 arr[i]=1 i=0
map[arr[i]]=1 arr[i]=7 i=1
map[arr[i]]=0 i - map[arr[i]]=2 i=2
map[arr[i]]=3 arr[i]=4 i=3
map[arr[i]]=4 arr[i]=3 i=4
map[arr[i]]=0 i - map[arr[i]]=5 i=5
map[arr[i]]=6 arr[i]=5 i=6
map[arr[i]]=4 i - map[arr[i]]=3 i=7
map[arr[i]]=3 i - map[arr[i]]=5 i=8
map[arr[i]]=9 arr[i]=9 i=9
map[arr[i]]=0 i - map[arr[i]]=10 i=10
map[arr[i]]=4 i - map[arr[i]]=7 i=11
10

*/

 



answered Dec 17, 2022 by avibootz
...