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
This Go code implements the maxDistants function, which finds the maximum distance to the nearest element with value 1 in an array of 0s and 1s.
The algorithm works as follows:
- Iterates through the array, keeping track of the index of the last found 1 (
lastOne). - If the current element is 1 and it's the first one found, the maximum distance is set to the index of this element (distance from the start).
- If it's not the first 1, it calculates half the distance between the current and the previous 1, updating the maximum.
- After the iteration, it checks the distance from the last 1 to the end of the array if there are zeros.
Example:
arr := []int{1, 0, 0, 0, 1}
fmt.Println(maxDistants(arr)) // Outputs 2
Here, the maximum distance is 2, which corresponds to the position between the two ones.
The function is useful, for example, for placing an element as far away as possible from others in a binary array.