// 演算法 / Algorithm:
// 先算出整個陣列的總和 total；再從左到右掃描，用 left 累積「左邊的和」，
// 右邊的和即為 total - left - nums[i]。每步取兩者差的絕對值。時間 O(n)。
// Compute the total once; sweep left-to-right keeping a running left sum,
// derive the right sum as total - left - nums[i], record the abs difference.

#include <stdlib.h>   // 提供 malloc / abs / Provides malloc and abs

// LeetCode 規定的函式簽名：回傳 int* 陣列，並透過 *returnSize 回報長度
// LeetCode's required signature: return an int* array and report its length via *returnSize
int* leftRightDifference(int* nums, int numsSize, int* returnSize) {
    *returnSize = numsSize;                          // 回傳陣列長度與輸入相同 / output has the same length n

    // 向系統要一塊能放 numsSize 個 int 的記憶體當作結果陣列
    // Allocate memory for numsSize ints to hold the answer
    int* answer = (int*)malloc(sizeof(int) * numsSize);

    long total = 0;                                  // 用 long 避免極端情況溢位 / long avoids any overflow risk
    for (int i = 0; i < numsSize; i++) {             // 第一次掃描：累加全部元素 / first pass: sum all elements
        total += nums[i];                            // total 變成整個陣列的和 / total becomes the whole-array sum
    }

    long left = 0;                                   // left = 目前下標「左邊」的元素和，初始為 0 / sum of elements before index i
    for (int i = 0; i < numsSize; i++) {             // 第二次掃描：逐位計算答案 / second pass: compute each answer
        long right = total - left - nums[i];         // 右邊和 = 全部 - 左邊 - 自己 / right sum = total minus left minus self
        long diff = left - right;                    // 左右差（可能為負）/ difference, may be negative
        if (diff < 0) diff = -diff;                  // 取絕對值：負數就變相反數 / take absolute value
        answer[i] = (int)diff;                       // 寫入結果，轉回 int / store result, cast back to int
        left += nums[i];                             // 把目前元素併入 left，供下一格使用 / extend left for the next index
    }

    return answer;                                   // 回傳結果陣列；呼叫者負責釋放 / caller frees this memory
}
