#include <string.h>   // strlen
#include <stdlib.h>   // malloc, free

/*
 * 演算法 / Algorithm:
 * 1) 統計 '1' 的總數作為基底 / count all '1's as the base.
 * 2) 把字串切成交替區段；對每個「左右都是 '0'」的 '1' 區段，
 *    delta = 左 '0' 長 + 右 '0' 長 / for each '1'-run flanked by zeros, delta = left0 + right0.
 * 3) 答案 = 基底 + 最大 delta / answer = base + max delta.
 */
int maxActiveSectionsAfterTrade(char* s) {
    int n = (int)strlen(s);            // n 是字串長度 / n is the string length

    int totalOnes = 0;                 // 目前的 '1' 總數（固定基底）/ base count of ones
    for (int i = 0; i < n; i++)        // 逐字掃描 / scan character by character
        if (s[i] == '1')               // s[i] 取第 i 個字元 / s[i] reads the i-th char
            totalOnes++;               // 遇到 '1' 就加一 / one more active section

    // runLen[k] / runCh[k]：第 k 個區段的長度與字元 / length & char of the k-th run.
    // 最多 n 個區段，所以配置 n 格 / at most n runs, so allocate n slots.
    int  *runLen = (int*)malloc(sizeof(int)  * (n > 0 ? n : 1)); // malloc 向系統要記憶體 / request memory
    char *runCh  = (char*)malloc(sizeof(char) * (n > 0 ? n : 1));
    int m = 0;                         // m 是已切出的區段數 / number of runs found so far

    int i = 0;                         // i 指向目前區段的起點 / start of the current run
    while (i < n) {                    // 掃完整個字串 / until we consume the whole string
        int j = i;                     // j 往右找相同字元的結尾 / j scans right while same char
        while (j < n && s[j] == s[i])  // 只要字元和起點一樣就前進 / advance while char matches
            j++;
        runCh[m]  = s[i];              // 這個區段的字元 / this run's character
        runLen[m] = j - i;             // 這個區段的長度 / this run's length
        m++;                           // 記錄一個新區段 / one more run recorded
        i = j;                         // 跳到下一個區段起點 / jump to next run's start
    }

    int best = 0;                      // 最大 delta，預設 0（不交易）/ max delta, default 0 (no trade)
    // 只看「中間」的區段：k 從 1 到 m-2，保證左右鄰居都存在
    // only interior runs (k in [1, m-2]) so both neighbors exist
    for (int k = 1; k + 1 < m; k++) {
        // 中間的 '1' 區段，其左右一定是 '0'（區段交替），仍明確檢查以求清楚
        // a '1'-run flanked by '0'-runs; runs alternate, but we check explicitly for clarity
        if (runCh[k] == '1' && runCh[k - 1] == '0' && runCh[k + 1] == '0') {
            int delta = runLen[k - 1] + runLen[k + 1]; // 左 '0' 長 + 右 '0' 長 / left0 + right0
            if (delta > best)          // 保留最大值 / keep the maximum
                best = delta;
        }
    }

    free(runLen);                      // 歸還記憶體，避免洩漏 / release memory to avoid a leak
    free(runCh);
    return totalOnes + best;           // 基底 + 最佳增量 / base + best delta
}
