Leetcode Problem 2256. Minimum Average Difference

2256. Minimum Average Difference

Leetcode Solutions

Prefix Sum Optimized Approach

  1. Initialize variables: 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).
  2. Calculate totalSum by iterating over the nums array.
  3. Iterate over each index 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.
  4. Return ans.
UML Thumbnail

Brute Force Approach

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...