// 演算法：邊用 %10 和 /10 拆出每一位數字，邊維護最大值 max1 與次大值 max2，
// 最後回傳 max1 * max2。單次掃描、常數空間。
// Algorithm: peel each digit with %10 and /10 while tracking the largest (max1)
// and second-largest (max2) digit; return max1 * max2. Single pass, O(1) space.
int maxProduct(int n) {
    int max1 = 0;                 // 目前最大的數字 / the largest digit seen so far
    int max2 = 0;                 // 目前次大的數字 / the second-largest digit so far

    while (n > 0) {               // 只要還有位數沒處理就繼續 / loop until all digits consumed
        int d = n % 10;          // 取出最右邊那位 / grab the rightmost digit (units place)

        if (d > max1) {          // 新數字比目前最大還大 / d beats the current maximum
            max2 = max1;         // 舊的最大降級為次大 / old max1 becomes the new second place
            max1 = d;            // 新數字成為最大 / d takes the top spot
        } else if (d > max2) {   // 不是最大，但比次大還大 / not the max, but beats second place
            max2 = d;            // 更新次大 / update the runner-up
        }

        n /= 10;                 // 切掉最右邊那位，往左移一位 / drop the processed digit
    }

    return max1 * max2;          // 最大兩位相乘即為答案 / product of the top two digits
}
