​​
问题:
一个数轴上共有N个点,第一个点的坐标是度度熊现在位置,第N-1个点是度度熊的家。现在他需要依次的从0号坐标走到N-1号坐标。
但是除了0号坐标和N-1号坐标,他可以在其余的N-2个坐标中选出一个点,并直接将这个点忽略掉,问度度熊回家至少走多少距离?

java代码实现:

package com.mingo.common;

import java.util.ArrayList;

public class DuDuXiongGoHome {

public static int GoHome(int n, ArrayList<Integer> list){
int result = 0;
int temp = 0;
int j=0;
for(int i=1;i<list.size()-1;i++){
int interval = Math.abs(list.get(i+1)-list.get(i)) + Math.abs(list.get(i)-list.get(i-1)) - Math.abs(list.get(i+1)-list.get(i-1));
if(interval>temp){
j=i;
temp = interval;
}
result += Math.abs(list.get(i+1)-list.get(i));
}
result = result + Math.abs(list.get(1)-list.get(0));
if(j>0){
System.out.println("跳过位置和数字为:("+j+","+list.get(j)+")");
result = result - temp;
}
return result;
}

public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0;i<4;i++){
int randInt = (int) ((Math.random()-0.5) * 10);
list.add(randInt);
}

System.out.println("输入数组为:");
for(Integer li:list){
System.out.print(li+", ");
}
System.out.println();
int value = GoHome(list.size(), list);
System.out.println("最短路径:"+value);
}

}