File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments