🚀

End of Year Sale: Use Coupon Code END2025 to Get Extra 25% Off.

12DAYS
:
04HOURS
:
10MINUTES
:
34SECONDS

Leetcode Problem 1685. Sum of Absolute Differences in a Sorted Array

1685. Sum of Absolute Differences in a Sorted Array

Leetcode Solutions

Calculating Prefix Sum on the Fly

  1. Initialize totalSum as the sum of all elements in nums.
  2. Initialize leftSum to 0.
  3. Initialize an empty list ans to store the result.
  4. Iterate over the indices i of nums: a. Calculate rightSum as totalSum - leftSum - nums[i]. b. Calculate leftCount as i. c. Calculate rightCount as len(nums) - 1 - i. d. Calculate leftTotal as leftCount * nums[i] - leftSum. e. Calculate rightTotal as rightSum - rightCount * nums[i]. f. Append leftTotal + rightTotal to ans. g. Add nums[i] to leftSum.
  5. Return ans.
UML Thumbnail

Brute Force Calculation

Ask Question

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

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...