1 solutions

  • 0
    @ 2025-7-31 19:59:25

    考虑做一个双指针,当颜色段数超过3时移动慢指针以减少颜色段数。对于每个快指针维护当前最长长度。最后输出这个长度即可。

    #include <bits/stdc++.h>
    using namespace std;
    const int N = 1e5 + 5;
    int n, num[N], ans;
    
    int main() {
    	cin >> n;
    	for(int i = 1;i <= n; ++i)
    		cin >> num[i];
    	int pos = 1, cnt = 0;
    	for(int i = 1;i <= n; ++i) {
    		if(num[i] != num[i - 1]) ++cnt;
    		while(cnt > 3) {
    			++pos;
    			if(num[pos] != num[pos - 1]) --cnt;
    		}
    		ans = max(ans, i - pos + 1);
    	}
    	cout << ans << endl;
    	return 0;
    }
    
    
    • 1

    Information

    ID
    19
    Time
    1000ms
    Memory
    256MiB
    Difficulty
    8
    Tags
    (None)
    # Submissions
    35
    Accepted
    6
    Uploaded By