Skip to content

Commit 954edcb

Browse files
committed
Two-Hundred-Fifty-Three Commit: Add Sum of Absolute Differences in a Sorted Array problem to Prefix Sum section
1 parent 5faec0d commit 954edcb

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package Prefix_Sum;
2+
3+
// Problem Statement: Sum of Absolute Differences in a Sorted Array (medium)
4+
// LeetCode Question: 1685. Sum of Absolute Differences in a Sorted Array
5+
6+
public class Problem_6_Sum_Of_Absolute_Differences_In_A_Sorted_Array {
7+
public int[] getSumAbsoluteDifferences(int[] nums) {
8+
int n = nums.length;
9+
int[] result = new int[n];
10+
int[] prefixSum = new int[n + 1];
11+
12+
// Calculate prefix sums
13+
for (int i = 0; i < n; i++) {
14+
prefixSum[i + 1] = prefixSum[i] + nums[i];
15+
}
16+
17+
// Calculate result array
18+
for (int i = 0; i < n; i++) {
19+
int leftSum = prefixSum[i];
20+
int rightSum = prefixSum[n] - prefixSum[i + 1];
21+
result[i] = i * nums[i] - leftSum + rightSum - (n - i - 1) * nums[i];
22+
}
23+
24+
return result;
25+
}
26+
}

0 commit comments

Comments
 (0)