How to find the maximum distance between two occurrences of same number in array with Go

1 Answer

0 votes
package main

import (
    "fmt"
)

func maxDistance(arr []int) int {
    indexMap := make(map[int]int)
    maxDist := 0

    for i, num := range arr {
        if firstIndex, found := indexMap[num]; found {
            dist := i - firstIndex
            if dist > maxDist {
                maxDist = dist
            }
        } else {
            indexMap[num] = i
        }
    }

    return maxDist
}

func main() {
    arr := []int{7, 1, 4, 3, 1, 5, 3, 4, 9, 1, 3}
    
    fmt.Println("Maximum distance between two occurrences of the same number:", maxDistance(arr))
}




/*
run:

Maximum distance between two occurrences of the same number: 8

*/

 



answered Jan 9, 2025 by avibootz
...