// 演算法 / Algorithm:
//   最有價值的子陣列是整個陣列,其值 = 全域最大 - 全域最小;選 k 次。
//   The best subarray is the whole array (max - min); choose it k times.
//   答案 = (max - min) * k,單次掃描 O(n)。
//   Answer = (max - min) * k, computed in a single O(n) pass.

class Solution {
public:
    long long maxTotalValue(vector<int>& nums, int k) {
        // max_element / min_element 是 STL <algorithm> 提供的函式,
        // 它們各掃描一次區間,回傳指向最大/最小元素的「迭代器」(類似指標)。
        // max_element / min_element (from <algorithm>) each scan the range
        // and return an iterator (pointer-like) to the largest / smallest element.
        // 前面加 '*' 是「解參考」,取出迭代器指向的實際數值。
        // The leading '*' dereferences the iterator to get the actual value.
        int mx = *max_element(nums.begin(), nums.end());  // 全域最大 / global max
        int mn = *min_element(nums.begin(), nums.end());  // 全域最小 / global min

        // 轉成 long long 再乘,避免 (10^9 * 10^5) 溢位 32 位元 int。
        // Cast to long long before multiplying so 10^9 * 10^5 doesn't overflow int.
        return static_cast<long long>(mx - mn) * k;
    }
};
