小信反转串 Wrong Answer 66 分 悬赏一个解决方案



我的代码:

#include<bits/stdc++.h>
using namespace std;
int maxsum;
int n, k;
string s;
int cnt;
int a[100005], sum[100005];
int main() {
	cin >> n >> k >> s;
	s = ' ' + s;
	for (int i = 1; i <= n; i++) {
		if (s[i] == '1') {
			int t1 = 0;
			while (i < n && s[i] == '1') {
				i++;
				t1++;
			}
			if (i == n && s[i] == '1') {
				i++;
				t1++;
			}
			i--;
			a[++cnt] = t1;
			t1 = 0;
		} else {
			int t2 = 0;
			while (i < n && s[i] == '0') {
				i++;
				t2++;
			}
			if (i == n && s[i] == '0') {
				i++;
				t2++;
			}
			i--;
			a[++cnt] = t2;
			t2 = 0;
		}
	}
	
	for (int i = 1; i <= cnt + 1; i++) {
		sum[i] = sum[i - 1] + a[i];
	}
	for (int i = 2 * k; i <= cnt + 1; i += 2) {
		maxsum = max(sum[i] - sum[i - 2 * k - 1], maxsum);
	}
	cout << maxsum;
	return 0;
}

2 个赞