// 演算法：把價格由大到小排序，每三顆一組，付前兩顆、第三顆免費。
// Algorithm: sort prices descending; per group of 3, pay the first two and the 3rd is free.
// 排序後索引 i 滿足 i % 3 == 2 的糖果免費，其餘累加。
// After sorting, candies at indices where i % 3 == 2 are free; sum the rest.

#include <vector>     // 提供 std::vector 動態陣列 / provides std::vector (dynamic array)
#include <algorithm>  // 提供 std::sort / provides std::sort

class Solution {
public:
    int minimumCost(std::vector<int>& cost) {
        // std::sort 預設由小到大，傳第三個參數可自訂順序。
        // std::sort defaults to ascending; a 3rd argument customizes the order.
        // 這裡用 lambda（匿名小函式）讓較大者排前面（降序）。
        // Here a lambda (anonymous inline function) puts larger values first (descending).
        std::sort(cost.begin(), cost.end(), [](int a, int b) {
            return a > b;  // a 在 b 前 ⟺ a 較大 / a comes before b when a is larger
        });

        int total = 0;  // 累計要付的錢 / running total of money paid.

        // 用索引走訪，方便用 i % 3 判斷組內位置。
        // Index-based loop so we can test position-in-group with i % 3.
        for (int i = 0; i < static_cast<int>(cost.size()); i++) {
            // 每組第三顆（i % 3 == 2）免費，略過。
            // The 3rd candy of each group (i % 3 == 2) is free — skip it.
            if (i % 3 == 2) {
                continue;  // 不加錢，直接進下一輪 / add nothing, move to next iteration.
            }
            total += cost[i];  // 其餘糖果付錢 / pay for every other candy.
        }

        return total;  // 回傳最小總花費 / return the minimum total cost.
    }
};
