Birch, then rowan…
Time limit1sMemory limit1024 MB
Given counts of K species, find the longest arrangement where every window of P consecutive trees holds distinct species.
- Level
Medium7 of 10
- Topics
- Greedy, Math, Sorting, Binary search
- Solved
- No attempts yet
Problem
To improve the city's landscaping and environment, the city administration has drafted a greening plan for the central avenue. Under the plan, a row of trees of (K) different species will be planted along one side of the avenue, and saplings were purchased for this purpose: (a_i) saplings of species (i).
For the planted row to be aesthetically perfect, any (P) consecutive trees must all be of different species. If the row has fewer than (P) trees, they must all be of different species.
Write a program that finds the maximum number of trees in an aesthetically perfect row planted from the purchased saplings.
Input
The first line of the input contains two integers: (K), the number of different tree species ((1 \le K \le 100,000)), and (P), the required number of consecutive trees of different species ((2 \le P \le K)). The following (K) lines contain integers (a_i), the number of purchased saplings of species (i) ((1 \le a_i \le 10^9)), one per line.
Output
The output must contain a single number: the maximum number of trees whose planting in a row in some order achieves aesthetic perfection.
Hint
In the example, the trees can be planted, for instance, in the order 2, 4, 3, 1, 2, 3, 1, 2.