/ SeriousOJ /

Record Detail

Wrong Answer


  
# Status Time Cost Memory Cost
#1 Wrong Answer 4ms 532.0 KiB

Code

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

int maxConsecutiveOnes(string &s, int n, int k) {
    vector<int> ones;
    vector<int> gaps;
    int maxOnes = 0;
    
    // Identify 1-segments and gaps
    int count = 0;
    bool inOnes = false;
    
    for (int i = 0; i < n; i++) {
        if (s[i] == '1') {
            if (!inOnes) {
                ones.push_back(1);
                inOnes = true;
            } else {
                ones.back()++;
            }
        } else {
            if (inOnes) {
                gaps.push_back(1);
                inOnes = false;
            } else if (!gaps.empty()) {
                gaps.back()++;
            }
        }
    }

    // Edge case: all `1`s or all `0`s
    if (ones.empty()) return min(k, n);
    if (gaps.empty()) return n;

    // Use a sliding window over the ones segments
    int left = 0, right = 0, usedK = 0, currentOnes = ones[0];

    while (right < gaps.size()) {
        if (usedK + gaps[right] <= k) {
            usedK += gaps[right];
            currentOnes += gaps[right] + ones[right + 1];
            right++;
        } else {
            maxOnes = max(maxOnes, currentOnes);
            usedK -= gaps[left];
            currentOnes -= gaps[left] + ones[left];
            left++;
        }
    }

    maxOnes = max(maxOnes, currentOnes);
    return maxOnes;
}

int main() {
    int t;
    cin >> t;
    
    while (t--) {
        int n, k;
        string s;
        cin >> n >> k >> s;
        
        cout << maxConsecutiveOnes(s, n, k) << endl;
    }
    
    return 0;
}

Information

Submit By
Type
Pretest
Problem
P1159 Binary String
Language
C++17 (G++ 13.2.0)
Submit At
2025-02-17 15:39:46
Judged At
2025-02-17 15:39:46
Judged By
Score
0
Total Time
4ms
Peak Memory
532.0 KiB