/*
 * 演算法 / Algorithm:
 * 單次掃描維護最大值與次大值，最後回傳 (max1-1)*(max2-1)。
 * One pass tracking the largest and second-largest, then return (max1-1)*(max2-1).
 */

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        // max1 目前最大值，max2 次大值；用 0 起始安全（所有元素 >= 1）
        // max1 = largest, max2 = second largest; start at 0 (all elements >= 1)
        int max1 = 0;
        int max2 = 0;

        // range-for：直接依序取出 vector 中每個元素，不必手動管理索引
        // range-for loop: iterate each element of the vector without manual indexing
        for (int num : nums) {
            if (num > max1) {
                // 舊 max1 降為 max2，新數字成為 max1
                // old max1 demoted to max2, new number becomes max1
                max2 = max1;
                max1 = num;
            } else if (num > max2) {
                // 只比 max2 大，更新次大值 / beats only max2, update it
                max2 = num;
            }
        }

        // 回傳兩個最大值各減 1 的乘積 / return product of the two largest, each minus 1
        return (max1 - 1) * (max2 - 1);
    }
};
