Sobes.tech
Middle — Senior

How to find the maximum number in an array that occurs only once?

sobes.tech AI

Answer from AI

To find the maximum number in an array that occurs exactly once, you can follow these steps:

  1. Count the occurrences of each number (for example, using a dictionary/hash table).
  2. Filter out the numbers that occur only once.
  3. Find the maximum among these numbers.

Example in Go:

package main

import (
    "fmt"
)

func maxUnique(nums []int) (int, bool) {
    counts := make(map[int]int)
    for _, num := range nums {
        counts[num]++
    }

    maxVal := 0
    found := false
    for num, count := range counts {
        if count == 1 {
            if !found || num > maxVal {
                maxVal = num
                found = true
            }
        }
    }
    return maxVal, found
}

func main() {
    arr := []int{2, 3, 5, 3, 7, 5, 8}
    if maxNum, ok := maxUnique(arr); ok {
        fmt.Println("Maximum number occurring exactly once:", maxNum)
    } else {
        fmt.Println("No numbers occur exactly once")
    }
}

If there are no numbers that occur exactly once in the array, the function returns false as the second parameter.