Sponsored
Sponsored
The naive approach involves calculating the summation of absolute differences directly for each element. For each element `nums[i]` in the array, iterate through every other element `nums[j]` and accumulate the absolute difference `|nums[i] - nums[j]|`. This results in a straightforward solution but with a time complexity of O(n^2)
due to the nested loops.
Time Complexity: O(n^2)
where n
is the length of the array.
Space Complexity: O(n)
for the result array.
1def getSumAbsoluteDifferences(nums):
2 result = []
3 for i in range(len(nums)):
4 sum_diff = 0
5 for j in range(len(nums)):
6 sum_diff += abs(nums[i] - nums[j])
7 result.append(sum_diff)
8 return result
9
10nums = [2, 3, 5]
11print(getSumAbsoluteDifferences(nums))
12
The Python solution utilizes two nested loops to compute the sum of absolute differences for each element. Each element's result is stored in a result
list, which is returned at the end.
To optimize the solution, use prefix sums to reduce redundant calculations. Compute prefix sums `leftSum` and `rightSum` to capture cumulative totals on each side of the current index. For each nums[i]
, compute the contribution using:
i
, each number nums[j]
contributes to |nums[i] - nums[j]|
as nums[i] - nums[j]
.i
to end, each number nums[j]
contributes as nums[j] - nums[i]
.Time Complexity: O(n)
as each element is processed only twice.
Space Complexity: O(n)
to store the result.
This C implementation uses cumulative `leftSum` and `rightSum` to keep track of elements processed. By adjusting these sums and using the formula, we efficiently calculate the results in O(n)
time.