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

#include <stdlib.h>  // 引入 qsort 所在的標頭檔 / header that provides qsort

// 比較函式：給 qsort 用，決定排序順序。
// Comparator: tells qsort how to order two elements.
// 回傳正數代表 a 該排在 b 後面，這裡讓「大的排前面」(降序)。
// Returning positive means a goes after b; here we put larger values first (descending).
static int cmpDesc(const void *a, const void *b) {
    // void* 是「不知道型別的指標」，先轉成 int* 再用 * 取出整數值。
    // void* is a type-less pointer; cast to int* then dereference (*) to read the int.
    int x = *(const int *)a;  // 取出第一個元素 / read the first element
    int y = *(const int *)b;  // 取出第二個元素 / read the second element
    return y - x;             // y - x 讓較大者排前面（降序）/ y - x sorts larger first (descending)
}

int minimumCost(int* cost, int costSize) {
    // 先就地把陣列由大到小排序 / sort the array in place, largest first.
    // 參數：陣列、元素個數、每個元素位元組數、比較函式。
    // Args: array, count, size of each element in bytes, comparator.
    qsort(cost, costSize, sizeof(int), cmpDesc);

    int total = 0;  // 累計要付的錢，初始為 0 / running sum of money we must pay, starts at 0.

    // 走過每一顆糖果 / iterate over every candy.
    for (int i = 0; i < costSize; i++) {
        // i % 3 == 2 表示這是每組的第三顆，免費，跳過不加錢。
        // i % 3 == 2 marks the 3rd candy of a group — it's free, so skip adding it.
        if (i % 3 == 2) {
            continue;  // 跳過本次迴圈剩下的部分 / skip the rest of this loop iteration.
        }
        total += cost[i];  // 其餘糖果都要付錢，累加價格 / all other candies are paid for.
    }

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