题解 | #合唱队#
合唱队
https://www.nowcoder.com/practice/6d9d69e3898f45169a441632b325c7b4
import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; public class Main { static int x = 0; static int y = 0; public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 int num = in.nextInt(); int temp = num; int len = 0; int[] nums = new int[num]; int[] left = new int[num]; int[] right = new int[num]; while (temp-- > 0) { // 注意 while 处理多个 case nums[len++] = in.nextInt(); } left = lengthOfLIS(nums, num); int[] nums2 = new int[num]; int j = 0; for (int i = num - 1; i >= 0; i--) { nums2[j++] = nums[i]; } right = lengthOfLIS(nums2, num); int minnum = left[0] + right[len - 1]; for (int k = 0; k < num ; k++) { minnum = Math.min(minnum, left[k] + right[num - 1 - k]); } System.out.println(minnum); } public static int[] lengthOfLIS(int[] nums, int len) { int [] dp = new int[len]; dp[0] = 1; int [] res = new int[len]; int maxnum = 1; for (int i = 0; i < len; i++) { dp[i] = 1; for (int j = 0; j < i; j++) { if (nums[i] > nums[j]) { dp[i] = Math.max(dp[i], dp[j] + 1); } } maxnum = Math.max(maxnum, dp[i]); res[i] = i + 1 - maxnum; } return res; } }