Link: https://leetcode.com/problems/minimum-average-difference/
Solution:
Topics: subarray
Intuition
Pretty basic problem with some annoying implementation and a division by zero edge case. Basically the idea is to keep a sum of the left partition an right partition and compute the average difference.
The first insight is that we only need the sum of the left partition…the sum of the right is just total_sum - left_sum
The second insight is that according to the problem statement, the left partition includes the value at the index, so the number of elements in the left is always i+1
. Ergo, the number of elements in the right is len(nums)-(i+1)
… which will lead to division by zero on the last index, so we must handle this edge case.
Implementation
Visual
Review 1
I initially thought to solve this with a prefix/suffix sum array but missed that you don’t need the suffix array because the sum of the right partition is simply total - left_sum
. So basically we must increment left_sum
by nums[i]
and derive right_sum
. To compute the average we must also divide by n
. In the case of the left partition n = i+1
and for the right n = len(nums) - (i+1)
. Compute the absolute difference and keep the min index.