Middle
import "fmt" func maxDistants(arr []int) int { maxDist := 0 lastOne := -1 for i := 0; i < len(arr); i++ { if arr[i] == 1 { if lastOne == -1 { maxDist = i } else { dist := (i - lastOne) / 2 if dist > maxDist { maxDist = dist } } lastOne = i } } if arr[len(arr)-1] == 0 { dist := len(arr) - 1 - lastOne if dist > maxDist { maxDist = dist } } return maxDist } func main() { fmt.Println(maxDistants([]int{1, 0, 0, 0, 1})) }
sobes.tech AI
Answer from AI
The maxDistants function in Go calculates the maximum distance to the nearest element with value 1 in an array of 0s and 1s. The idea is to find a position where a 1 can be placed so that the distance to the nearest existing 1 is maximized.
Logic explanation:
- The variable
lastOnestores the index of the last encountered 1. - As the array is traversed, if a 1 is encountered:
- If it's the first 1, the maximum distance is the index of this 1 (distance from the start).
- Otherwise, we consider half the distance between the current and the previous 1 (since we can stand in the middle).
- After traversal, we check if there are zeros to the right of the last 1, and update the maximum distance if needed.
Example usage:
package main
import "fmt"
func maxDistants(arr []int) int {
maxDist := 0
lastOne := -1
for i := 0; i < len(arr); i++ {
if arr[i] == 1 {
if lastOne == -1 {
maxDist = i
} else {
dist := (i - lastOne) / 2
if dist > maxDist {
maxDist = dist
}
}
lastOne = i
}
}
if arr[len(arr)-1] == 0 {
dist := len(arr) - 1 - lastOne
if dist > maxDist {
maxDist = dist
}
}
return maxDist
}
func main() {
fmt.Println(maxDistants([]int{1, 0, 0, 0, 1})) // Outputs 2
}
This code correctly works for finding the maximum distance to the nearest 1, considering the edges of the array.