Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit e7ab7a1

Browse files
committed
Add solution #1685
1 parent 998d615 commit e7ab7a1

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,472 LeetCode solutions in JavaScript
1+
# 1,473 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -1297,6 +1297,7 @@
12971297
1680|[Concatenation of Consecutive Binary Numbers](./solutions/1680-concatenation-of-consecutive-binary-numbers.js)|Medium|
12981298
1681|[Minimum Incompatibility](./solutions/1681-minimum-incompatibility.js)|Hard|
12991299
1684|[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|
13001301
1716|[Calculate Money in Leetcode Bank](./solutions/1716-calculate-money-in-leetcode-bank.js)|Easy|
13011302
1718|[Construct the Lexicographically Largest Valid Sequence](./solutions/1718-construct-the-lexicographically-largest-valid-sequence.js)|Medium|
13021303
1726|[Tuple with Same Product](./solutions/1726-tuple-with-same-product.js)|Medium|
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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+
};

0 commit comments

Comments
 (0)