/*
 * 演算法 / Algorithm:
 * 貪心法：對每一對相鄰日期，把正向價差加進總利潤。
 * Greedy: for every adjacent pair of days, add the positive diff to total profit.
 * 一次線性掃描即可，O(n) 時間 / O(1) 空間。
 * One linear pass — O(n) time, O(1) extra space.
 */

class Solution {
public:
    int maxProfit(std::vector<int>& prices) {
        // profit 累計總利潤 / running total of profit
        // 使用 int 即可：n ≤ 3e4 且 price ≤ 1e4，最大利潤遠小於 INT_MAX
        // int is safe here: with n ≤ 3e4 and price ≤ 1e4, profit fits in int
        int profit = 0;

        // range-for 從索引 1 不太方便，改用傳統 for 迴圈以便存取 i-1
        // Using an indexed for-loop because we need both prices[i] and prices[i-1]
        // size() 回傳 size_t (無號)，這裡 prices 不為空所以安全
        // size() returns size_t (unsigned); prices is guaranteed non-empty by constraints
        for (size_t i = 1; i < prices.size(); ++i) {
            // 計算相鄰兩天的價差 / compute the difference between today and yesterday
            int diff = prices[i] - prices[i - 1];

            // std::max(a, b) 取兩者中較大者；diff 為負時取 0，相當於忽略下跌
            // std::max picks the larger of two values; clipping negatives to 0
            // skips losing days without an explicit if-statement
            profit += std::max(diff, 0);
        }

        // 回傳最大利潤 / return the maximum profit
        return profit;
    }
};
