#include <string>
#include <vector>
#include <utility>     // std::pair
#include <algorithm>   // std::count, std::max
using namespace std;

/*
 * 演算法 / Algorithm: 與 C 版相同 / same as the C version —
 * 統計 '1' 總數，切成交替區段，對每個被 '0' 包夾的 '1' 區段取
 * (左 '0' 長 + 右 '0' 長) 的最大值當 delta，答案 = 總數 + delta。
 * Count ones, split into runs, and for each '1'-run surrounded by '0'-runs
 * take max(left0 + right0) as delta; answer = totalOnes + delta.
 */
class Solution {
public:
    int maxActiveSectionsAfterTrade(string s) {
        int n = (int)s.size();                       // 字串長度 / string length

        // count 是 STL 演算法，數出區間內等於 '1' 的個數 / std::count tallies '1's in the range
        int totalOnes = (int)count(s.begin(), s.end(), '1');

        // runs：每個元素是 {字元, 長度} 的 pair / each element is a {char, length} pair.
        // vector 是可自動增長的陣列 / vector is a dynamic (auto-growing) array.
        vector<pair<char, int>> runs;
        for (int i = 0; i < n; ) {                   // 外層不自增，內層跳到下一區段 / i jumps run by run
            int j = i;                               // j 找相同字元的結尾 / extend while char is equal
            while (j < n && s[j] == s[i]) j++;
            runs.push_back({s[i], j - i});           // 記錄 {字元, 長度} / store {char, length}
            i = j;                                   // 前進到下一區段 / move to next run
        }

        int best = 0;                                // 最大 delta / max delta (0 = no trade)
        // k 從 1 到 size-2，確保 runs[k-1] 與 runs[k+1] 都存在
        // k in [1, size-2] so both neighbors exist
        for (int k = 1; k + 1 < (int)runs.size(); k++) {
            // 中間被 '0' 包夾的 '1' 區段 / a '1'-run surrounded by '0'-runs
            if (runs[k].first == '1' &&
                runs[k - 1].first == '0' &&
                runs[k + 1].first == '0') {
                // .second 取 pair 的第二個值（長度）/ .second is the pair's length field
                best = max(best, runs[k - 1].second + runs[k + 1].second);
            }
        }

        return totalOnes + best;                     // 基底 + 最佳增量 / base + best delta
    }
};
