/*
 * 演算法 / Algorithm:
 * 只跟「最大值 max1」與「次大值 max2」有關，所以單次掃描維護這兩個值即可。
 * We only need the two largest values, so one pass tracking max1 and max2 suffices.
 * 最後回傳 (max1-1)*(max2-1)。 / Finally return (max1-1)*(max2-1).
 */

int maxProduct(int* nums, int numsSize) {
    // max1 是目前最大值，max2 是次大值；起始 0 安全，因為所有 nums[i] >= 1
    // max1 = largest so far, max2 = second largest; 0 is a safe start since all nums[i] >= 1
    int max1 = 0;
    int max2 = 0;

    // 從頭到尾走過陣列一次 / walk through the array exactly once
    for (int i = 0; i < numsSize; i++) {
        int num = nums[i];  // 取出目前這個數字 / read the current element

        if (num > max1) {
            // 新數字比最大值還大：舊的 max1 降級為 max2，新數字成為 max1
            // new number beats the max: old max1 becomes max2, new number becomes max1
            max2 = max1;
            max1 = num;
        } else if (num > max2) {
            // 新數字比不過 max1，但比 max2 大：只更新 max2
            // beats only the second largest: update max2 only
            max2 = num;
        }
        // 否則 num 太小，兩個都不更新 / otherwise num is too small, no update
    }

    // 兩個最大值各減 1 後相乘就是答案 / multiply the two largest (each minus 1)
    return (max1 - 1) * (max2 - 1);
}
