✅ [Python/C++] running prefix & suffix (explained)
\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.\n*\nThis solution employs computing running prefix and suffix of the input array. Time complexity is linear: *O
**\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.**\n****\nThis solution employs computing running prefix and suffix of the input array. Time complexity is linear: **O(N)**. Space complexity is constant: **O(1)**.\n****\n\n**Python #1.** First, linear-space solution with precomputed prefix & suffix.\n```\nimport numpy as np\n\nclass Solution:\n    def minimumAverageDifference(self, nums: List[int]) -> int:\n        \n        first, last = [], [0]\n        f = l = 0\n        \n        for i,n in enumerate(nums,start=1):\n            first.append((f:=f+n) // i)\n\n        for i,n in enumerate(reversed(nums[1:]),start=1):\n            last.append((l:=l+n) // i)\n            \n        last.reverse()\n        \n        diff = [abs(f-l) for f,l in zip(first,last)]\n        \n        return np.argmin(diff)\n```\n\n**Python #2.** Constant-space solution with running prefix & suffix.\n```\nclass Solution:\n    def minimumAverageDifference(self, nums: List[int]) -> int:\n        \n        i, m = 0, inf                        # running prefix starts from 0\n        pfx, sfx = 0, sum(nums)              # running suffix starts from sum of array\n        \n        for j,n in enumerate(nums,start=1):\n            pfx, sfx = pfx+n, sfx-n          # update prefix (+) and suffix (-)\n            k = len(nums)-j or 1             # prevent suffix length to be 0\n            d = abs(pfx//j - sfx//k)\n            if d < m:\n                m, i = d, j-1\n\n        return i\n```\n\n**C++.** Constant-space solution with running prefix & suffix.\n```\nclass Solution \n{\npublic:\n    int minimumAverageDifference(vector<int>& nums) \n    {\n        long i = 0, j = 0, m = LONG_MAX, k, d;\n        long pfx = 0, sfx = accumulate(nums.begin(), nums.end(), 0L);\n        \n        for (int n : nums)\n        {\n            pfx += n, sfx -= n, j += 1;\n            k = nums.size() - j;\n            d = abs(pfx/j - sfx/(k?k:1));\n            if (d < m) m = d, i = j - 1;\n        }\n        \n        return i;\n    }\n};\n```
[]