n
(number of elements in the array), minAvgDiff
(large integer value for minimum average difference), totalSum
(sum of all elements), currPrefixSum
(sum of elements up to current index), and ans
(index with minimum average difference).totalSum
by iterating over the nums
array.i
of the nums
array:
a. Add the current element to currPrefixSum
.
b. Calculate the average of the left part using currPrefixSum
divided by i + 1
.
c. Calculate the average of the right part using (totalSum - currPrefixSum)
divided by n - i - 1
.
d. Calculate the absolute difference between the two averages.
e. If this difference is smaller than minAvgDiff
, update minAvgDiff
and ans
with the current index i
.ans
.