数组K段划分最值判定解法未通过隐藏测试用例,求技术排查
Alright, let's break down the issue here. Your core idea works for most cases, but you missed a critical edge scenario: when K equals 1.
The Root Cause
Your logic assumes you can always split the array to isolate the minimum element into its own segment. But when K=1, you have no choice but to take the entire array as a single segment. In this case, the array P (which holds the max of each segment) will only contain the maximum value of the entire array, so S (the minimum of P) is that maximum value—not the array's minimum.
Your original code completely ignores this case, which is exactly why that hidden test case failed.
Correct Approach
We need to split the problem into two scenarios:
- Case 1: K > 1: We can always isolate the array's minimum into its own segment (since K ≤ N, we can split the rest of the elements into K-1 non-empty segments). Here,
Sis the array's minimum, just like your original logic. - Case 2: K = 1: We have to use the entire array as one segment, so
Sis the array's maximum. We compare this value with Q instead.
Fixed Code
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); int t = s.nextInt(); int n, k, q, i; while (t-- > 0) { n = s.nextInt(); k = s.nextInt(); q = s.nextInt(); int[] a = new int[n]; for (i = 0; i < n; i++) a[i] = s.nextInt(); if (k == 1) { // Calculate max of the entire array int max = a[0]; for (i = 1; i < n; i++) { if (a[i] > max) { max = a[i]; } } if (max < q) { System.out.println(max); } else { System.out.println("NO"); } } else { // Original logic works here: find min of array int minIdx = 0; for (i = 1; i < n; i++) { if (a[i] < a[minIdx]) { minIdx = i; } } if (a[minIdx] < q) { System.out.println(a[minIdx]); } else { System.out.println("NO"); } } } s.close(); } }
Example to Verify
Let's take a test case that would have broken your original code:
Input:
1
3 1 5
3 1 4
- Your original code would output
1(the array's min), but the correctSis4(the array's max, since we can only have one segment). Since 4 < 5, the correct output is4.
Another test case:
Input:
1
3 1 3
3 1 4
- The max is 4, which is ≥ 3, so output should be
NO.
内容的提问来源于stack exchange,提问作者windstorm

