File tree Expand file tree Collapse file tree 2 files changed +36
-1
lines changed Expand file tree Collapse file tree 2 files changed +36
-1
lines changed Original file line number Diff line number Diff line change 1- # 1,472 LeetCode solutions in JavaScript
1+ # 1,473 LeetCode solutions in JavaScript
22
33[ https://leetcodejavascript.com ] ( https://leetcodejavascript.com )
44
129712971680|[ Concatenation of Consecutive Binary Numbers] ( ./solutions/1680-concatenation-of-consecutive-binary-numbers.js ) |Medium|
129812981681|[ Minimum Incompatibility] ( ./solutions/1681-minimum-incompatibility.js ) |Hard|
129912991684|[ Count the Number of Consistent Strings] ( ./solutions/1684-count-the-number-of-consistent-strings.js ) |Easy|
1300+ 1685|[ Sum of Absolute Differences in a Sorted Array] ( ./solutions/1685-sum-of-absolute-differences-in-a-sorted-array.js ) |Medium|
130013011716|[ Calculate Money in Leetcode Bank] ( ./solutions/1716-calculate-money-in-leetcode-bank.js ) |Easy|
130113021718|[ Construct the Lexicographically Largest Valid Sequence] ( ./solutions/1718-construct-the-lexicographically-largest-valid-sequence.js ) |Medium|
130213031726|[ Tuple with Same Product] ( ./solutions/1726-tuple-with-same-product.js ) |Medium|
Original file line number Diff line number Diff line change 1+ /**
2+ * 1685. Sum of Absolute Differences in a Sorted Array
3+ * https://leetcode.com/problems/sum-of-absolute-differences-in-a-sorted-array/
4+ * Difficulty: Medium
5+ *
6+ * You are given an integer array nums sorted in non-decreasing order.
7+ *
8+ * Build and return an integer array result with the same length as nums such that result[i] is
9+ * equal to the summation of absolute differences between nums[i] and all the other elements
10+ * in the array.
11+ *
12+ * In other words, result[i] is equal to sum(|nums[i]-nums[j]|) where 0 <= j < nums.length
13+ * and j != i (0-indexed).
14+ */
15+
16+ /**
17+ * @param {number[] } nums
18+ * @return {number[] }
19+ */
20+ var getSumAbsoluteDifferences = function ( nums ) {
21+ const n = nums . length ;
22+ const result = new Array ( n ) ;
23+ let prefixSum = 0 ;
24+ let suffixSum = nums . reduce ( ( sum , num ) => sum + num , 0 ) ;
25+
26+ for ( let i = 0 ; i < n ; i ++ ) {
27+ const current = nums [ i ] ;
28+ suffixSum -= current ;
29+ result [ i ] = ( current * i - prefixSum ) + ( suffixSum - current * ( n - 1 - i ) ) ;
30+ prefixSum += current ;
31+ }
32+
33+ return result ;
34+ } ;
You can’t perform that action at this time.
0 commit comments