得物笔试ac
第一题以最后一个元素为中心一直往前环就可以
注意边界条件可能是a[1]-a[0]。
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int[n]; for (int i = 0; i < a.length; i++) { a[i] = sc.nextInt(); } Arrays.sort(a); int max = a[1] - a[0]; if (n > 2) { max = a[2] - a[0]; } int i = n - 2; while (i >= 2) { int cur = Math.max(a[i + 1] - a[i - 1], a[i] - a[i - 2]); max = Math.max(max, cur); i -= 2; } System.out.print(max); } }
第二题,记录所有数字求和到n的最小次数
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); int M = scanner.nextInt(); int[] numbers = new int[N]; for (int i = 0; i < N; i++) { numbers[i] = scanner.nextInt(); } Arrays.sort(numbers); int result = findMinNumbers(numbers, M); if (result == Integer.MAX_VALUE) { System.out.println("No solution"); } else { System.out.println(result); } } public static int findMinNumbers(int[] numbers, int target) { int[] dp = new int[target + 1]; Arrays.fill(dp, Integer.MAX_VALUE); dp[0] = 0; for (int num : numbers) { for (int i = target; i >= num; i--) { if (dp[i - num] != Integer.MAX_VALUE) { dp[i] = Math.min(dp[i], dp[i - num] + 1); } } } return dp[target]; } }