🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line
\uD83D\uDD34 Check out LeetCode The Hard Way for more solution explanations and tutorials. \n\uD83D\uDFE0 Check out our Discord for live discussion.\n\uD83D\uDF
\uD83D\uDD34 Check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. \n\uD83D\uDFE0 Check out our [Discord](https://discord.gg/Nqm4jJcyBf) for live discussion.\n\uD83D\uDFE2 Give a star on [Github Repository](https://github.com/wingkwong/leetcode-the-hard-way) and upvote this post if you like it.\n\n---\n\n```cpp\nclass Solution {\npublic:\n    int minimumAverageDifference(vector<int>& nums) {\n        int ans = 0, n = nums.size(), mi = INT_MAX;\n        // since we need the sum for first i + 1 and last n - i - 1 elements\n        // we can pre-calculate it first\n        // it is called prefix sum and suffix sum\n        vector<long long> pref(n);\n        // prev[0] is the first element\n        pref[0] = nums[0];\n        // starting from i = 1, pref[i] is the sum + the current element\n        for (int i = 1; i < n; i++) pref[i] = pref[i - 1] + nums[i];\n        // then we can iterate each number\n        for (int i = 0; i < n; i++) {\n            // now we know the prefix sum\n            // the suffix sum is simply pref[n - 1] - pref[i]\n            long long k = abs((pref[i] / (i + 1)) - ((pref[n - 1] - pref[i]) / max(n - i - 1, 1)));\n            // check the min and update ans\n            if (k < mi) {\n                mi = k;\n                ans = i;\n            }\n        }\n        return ans;\n    }\n};\n```
['C', 'Prefix Sum', 'C++']