C - Colorful Candies
Problem Statement
There are N candies arranged in a row from left to right.
Each of these candies has one color that is one of the 109 colors called Color 1, Color 2, …, and Color 109.
For each i=1,2,…,N, the color of the i-th candy from the left is Color ci.
From this row, Takahashi can choose K consecutive candies and get them.
That is, he can choose an integer i such that 1≤i≤N−K+1 and get the i-th, (i+1)-th, (i+2)-th, …, (i+K−1)-th candy from the left.
Takahashi likes to eat colorful candies, so the more variety of colors his candies have, the happier he will be.
Print the maximum possible number of distinct colors in candies he gets.
Constraints
1≤K≤N≤3×105
1≤ci≤109
All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
c1 c2 … cN
Output
Print the maximum possible number of distinct colors in candies Takahashi gets.
Sample Input 1
7 3
1 2 1 2 3 3 1
Sample Output 1
3
Sample Input 2
5 5
4 4 4 4 4
Sample Output 2
1
Sample Input 3
10 6
304621362 506696497 304621362 506696497 834022578 304621362 414720753 304621362 304621362 414720753
Sample Output 3
4
题目大意:
Takahashi有n种糖,一种数字代表一种糖。给n个数字和区间长度,问所有满足长度要求的区间内糖的种类最大是多少,输出最大的种类数。
题解:
可以将一个区间的数都装进map里,map.size()就是区间内的数字的种类。求下一个区间只需要将最左边的一个数字map中的value减一,再将右边一个数map中的value加一即可。注意当一种数字在map中的vlaue为0时记得map.erase()这个数字。
统计map.size()出现过的最大值输出即可。
AC代码:
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <cstring>
#include <cmath>
using namespace std;
typedef long long ll;
const int N = 1e6 + 5;
const int INF = 0x3f3f3f3f;
ll a[N];
int main() {
ll n, k;
cin >> n >> k;
map<ll, ll> mp;
for (ll i = 0; i < n; i ++) cin >> a[i]; // 读入数字
ll mx = -1; // 种类最大值
for (ll i = 0; i < n; i ++) {
mp[a[i]] ++; // 将右边的数添加进map,区间移动
if (i + 1 >= k) { // 第一个区间的长度满足后开始区间移动
ll t = mp.size();
mx = max(mx, t); // 记录种类最大值
mp[a[i - k + 1]] --; // 删除最左边的数字,区间移动
if (mp[a[i - k + 1]] == 0) mp.erase(a[i - k + 1]); // 如果数字数量为0则erase
}
}
cout << mx << '\n'; // 输出最大值
return 0;
}