Explanation
We can binary search over the largest possible median that is possible to achieve.
To check whether the median is achievable on an interval, we need to count the number of elements that are and the number of elements that are .
If the number of elements is greater than the number of elements , we can say that this median is achievable. Note that there must be strictly more elements greater than or equal to than less than because of how the problem defines the median for subarrays even sizes.
Let be the number of elements in the prefix that are - the number of elements in the prefix that are .
We can prove that if and , it is possible to have a median of . This is because on the range from to there will be more elements greater than or equal to than less than which means that the median will also be greater than or equal to .
From here we can perform a linear search for the max difference keeping track of the minimum element in the prefix from to which ensures that the size is always at least . If it greater than , then this median is possible to achieve.
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;int main() {int n, k;cin >> n >> k;vector<int> a(n);for (int &i : a) { cin >> i; }// Binary search for the maximum median
Java
import java.io.*;import java.util.*;public class MaxMedian {public static void main(String[] args) throws Exception {BufferedReader br = new BufferedReader(new InputStreamReader(System.in));PrintWriter pw = new PrintWriter(System.out);StringTokenizer st = new StringTokenizer(br.readLine());int n = Integer.parseInt(st.nextToken());
Python
n, k = [int(i) for i in input().split()]a = [int(i) for i in input().split()]# Binary search over the maximum medianlo = 1hi = nwhile lo < hi:median = (lo + hi + 1) // 2# Same as the f described in the editorialf = []
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!