How to find the maximum distance between two numbers in a slice with Go

1 Answer

0 votes
package main

import (
	"fmt"
)

// maxInt returns the maximum of two integers.
func maxInt(a, b int) int {
	if a > b {
		return a
	}
	return b
}

// absInt returns the absolute value of an integer.
func absInt(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

// MaxDistanceBetweenNumbers finds the maximum distance (absolute index difference) 
// between two numbers in a slice. Returns the distance and true if both numbers exist, 
// or 0 and false otherwise.
func MaxDistanceBetweenNumbers(slice []int, num1, num2 int) (int, bool) {
	// Variables to track the first and last occurrences of both numbers
	first1, last1 := -1, -1
	first2, last2 := -1, -1

	// Single pass through the slice: O(N) time complexity, O(1) space complexity
	for i, current := range slice {
		if current == num1 {
			if first1 == -1 {
				first1 = i // Record the first time num1 appears
			}
			last1 = i // Continuously update the last time num1 appears
		} else if current == num2 {
			if first2 == -1 {
				first2 = i // Record the first time num2 appears
			}
			last2 = i // Continuously update the last time num2 appears
		}
	}

	// Edge case: If either number is not present in the slice, return false
	if first1 == -1 || first2 == -1 {
		return 0, false
	}

	// The maximum distance is always between the outermost boundaries of the two sets:
	// 1. Distance between the first occurrence of num1 and the last occurrence of num2
	// 2. Distance between the last occurrence of num1 and the first occurrence of num2
	dist1 := absInt(first1 - last2)
	dist2 := absInt(last1 - first2)

	return maxInt(dist1, dist2), true
}

func main() {
	// --- Example Usage ---
	slice := []int{2, 3, 7, 3, 3, 4, 8, 8, 8, 11, 9, 1, 3}
	number1 := 3
	number2 := 8

	if result, found := MaxDistanceBetweenNumbers(slice, number1, number2); found {
		fmt.Printf("The maximum distance between %d and %d is: %d\n", number1, number2, result)
	} else {
		fmt.Printf("One or both numbers (%d, %d) were not found in the slice.\n", number1, number2)
	}
}



/*
run:

The maximum distance between 3 and 8 is: 7

*/

 



answered Oct 22 by avibootz
...