2021-03-10: There are N points in an array, the point with sequence number 0 is the starting position, and the point with sequence number N-1 is the ending position. Now we need to walk from point 0 to point N-1 in sequence. But in addition to point 0 and point N-1, he can select a point from the remaining N-2 positions and ignore this point directly, asking how much distance is at least from the start point to the end point?
Fu Ge's answer 2021-03-10:
Array [1,4,-1,3], ignoring the sequence number 1, the array becomes [1,-1,3], the distance is abs(-2)+4=6; ignoring the sequence number 2, the array becomes [1, 4,3], the distance is 3+1=4.
Select a point from N-2 coordinates and ignore this point directly. Ignoring a point directly will only directly affect the distance between the nodes before and after the node. This distance of influence is temporarily named as the optimized distance, and all the nodes are formed into a set of three nodes in order. In this way, the result can be obtained by only passing through one cycle.
The code is written in golang, the code is as follows:
package main
import "fmt"
func main() {
arr := []int{1, 4, -1, 3}
fmt.Println(shortDistance(arr))
}
func shortDistance(arr []int) int {
arrLen := len(arr)
if arrLen <= 1 {
return 0
}
if arrLen <= 3 {
return abs(arr[arrLen-1] - arr[0])
}
i1 := arr[1] - arr[0]
i2 := 0
maxval := 0 //最大优化距离
ret := abs(i1) //所有相邻两边距离之和
for i := 1; i < arrLen-1; i++ {
i2 = arr[i+1] - arr[i]
maxval = getMax(maxval, abs(i2)+abs(i1)-abs(i2+i1))
i1 = i2
ret += abs(i1)
}
return ret - maxval
}
func abs(a int) int {
if a < 0 {
return -a
} else {
return a
}
}
func getMax(a int, b int) int {
if a > b {
return a
} else {
return b
}
}
The execution results are as follows: