Skip to content

Commit dd9ed8a

Browse files
add 1685
1 parent ecda9e4 commit dd9ed8a

File tree

3 files changed

+47
-0
lines changed

3 files changed

+47
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ _If you like this project, please leave me a star._ ★
88

99
| # | Title | Solutions | Video | Difficulty | Tag
1010
|-----|----------------|---------------|--------|-------------|-------------
11+
|1685|[Sum of Absolute Differences in a Sorted Array](https://leetcode.com/problems/sum-of-absolute-differences-in-a-sorted-array/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_1685.java) ||Medium|Math, Greedy|
1112
|1684|[Count the Number of Consistent Strings](https://leetcode.com/problems/count-the-number-of-consistent-strings/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_1684.java) ||Easy|String|
1213
|1679|[Max Number of K-Sum Pairs](https://leetcode.com/problems/max-number-of-k-sum-pairs/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_1679.java) ||Medium|HashTable|
1314
|1678|[Goal Parser Interpretation](https://leetcode.com/problems/goal-parser-interpretation/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_1678.java) ||Easy|String|
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.fishercoder.solutions;
2+
3+
public class _1685 {
4+
public static class Solution1 {
5+
public int[] getSumAbsoluteDifferences(int[] nums) {
6+
int len = nums.length;
7+
int[] preSums = new int[len];
8+
for (int i = 1; i < len; i++) {
9+
preSums[i] = preSums[i - 1] + nums[i - 1];
10+
}
11+
int[] postSums = new int[len];
12+
for (int i = len - 2; i >= 0; i--) {
13+
postSums[i] = postSums[i + 1] + nums[i + 1];
14+
}
15+
int[] result = new int[len];
16+
for (int i = 0; i < len; i++) {
17+
result[i] = nums[i] * i - preSums[i] + postSums[i] - nums[i] * (len - i - 1);
18+
}
19+
return result;
20+
}
21+
}
22+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.fishercoder;
2+
3+
import com.fishercoder.solutions._1685;
4+
import org.junit.BeforeClass;
5+
import org.junit.Test;
6+
7+
import static org.junit.Assert.assertArrayEquals;
8+
9+
public class _1685Test {
10+
private static _1685.Solution1 solution1;
11+
private static int[] nums;
12+
13+
@BeforeClass
14+
public static void setup() {
15+
solution1 = new _1685.Solution1();
16+
}
17+
18+
@Test
19+
public void test1() {
20+
nums = new int[]{2, 3, 5};
21+
assertArrayEquals(new int[]{4, 3, 5}, solution1.getSumAbsoluteDifferences(nums));
22+
}
23+
24+
}

0 commit comments

Comments
 (0)