绝对值函数求极值,模拟即可:
import java.util.*; public class Main { public static void main(String[] args) throws Exception{ Scanner sc = new Scanner(System.in); int[] v = new int[4]; for(int i = 0; i < 4; ++i) v[i] = sc.nextInt(); Arrays.sort(v); int r = Integer.MAX_VALUE; for(int i = v[0]; i <= v[3]; ++i){ int sum = 0; for(int j = 0; j <= 3; ++j){ sum += Math.abs(v[j] - i); } if(r > sum) r = sum; } System.out.println(r); } }