AtCoder Beginner Contest 210 C - Colorful Candies

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;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值