// 演算法 / Algorithm:
// 先求整個陣列的總和 total；再線性掃描，用 left 維護「左邊的和」，
// 右邊的和 = total - left - nums[i]，每步存入兩者差的絕對值。時間 O(n)。
// Compute total once, then sweep with a running left sum; right = total - left - nums[i].

#include <vector>     // 提供 std::vector 動態陣列 / provides the std::vector dynamic array
#include <numeric>    // 提供 std::accumulate 求和 / provides std::accumulate for summing
#include <cstdlib>    // 提供 std::abs / provides std::abs

class Solution {
public:
    std::vector<int> leftRightDifference(std::vector<int>& nums) {
        int n = nums.size();                         // n 是陣列大小 / n is the array length
        std::vector<int> answer(n);                  // 預先配置長度 n 的結果向量 / preallocate the answer vector

        // accumulate 把 nums 全部加起來；起始值寫 0L 讓累加用 long，避免溢位
        // accumulate sums the whole vector; the 0L seed accumulates in long to avoid overflow
        long total = std::accumulate(nums.begin(), nums.end(), 0L);

        long left = 0;                               // left = 當前下標左側元素之和 / sum of elements before index i
        for (int i = 0; i < n; i++) {                // 線性掃描每個下標 / linear sweep over indices
            long right = total - left - nums[i];     // 右側和由總和推得 / right sum derived from total
            answer[i] = std::abs(left - right);      // 存入左右差的絕對值 / store the absolute difference
            left += nums[i];                         // 更新 left 以維持不變量 / update left to keep the invariant
        }

        return answer;                               // 回傳向量，無需手動釋放 / return by value, no manual free
    }
};
