Skip to content

Commit 275ac25

Browse files
committed
Add MaximumGap leetcode task solution
1 parent bedba7e commit 275ac25

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package by.andd3dfx.common;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* <pre>
7+
* https://leetcode.com/problems/maximum-gap/description/
8+
*
9+
* Given an integer array nums, return the maximum difference between two successive elements in its sorted form.
10+
* If the array contains less than two elements, return 0.
11+
* You must write an algorithm that runs in linear time and uses linear extra space.
12+
*
13+
* Example 1:
14+
* Input: nums = [3,6,9,1]
15+
* Output: 3
16+
* Explanation: The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3.
17+
*
18+
* Example 2:
19+
* Input: nums = [10]
20+
* Output: 0
21+
* Explanation: The array contains less than 2 elements, therefore return 0.
22+
* </pre>
23+
*/
24+
public class MaximumGap {
25+
26+
public static int determine(int[] nums) {
27+
if (nums.length < 2) {
28+
return 0;
29+
}
30+
31+
Arrays.sort(nums);
32+
33+
int result = 0;
34+
for (int i = 1; i < nums.length; i++) {
35+
var diff = nums[i] - nums[i - 1];
36+
if (diff > result) {
37+
result = diff;
38+
}
39+
}
40+
return result;
41+
}
42+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package by.andd3dfx.common;
2+
3+
import org.junit.Test;
4+
5+
import static by.andd3dfx.common.MaximumGap.determine;
6+
import static org.assertj.core.api.Assertions.assertThat;
7+
8+
public class MaximumGapTest {
9+
10+
@Test
11+
public void testDetermine() {
12+
assertThat(determine(new int[]{3, 6, 9, 1})).isEqualTo(3);
13+
assertThat(determine(new int[]{3, 49, 1, 9, 2})).isEqualTo(40);
14+
assertThat(determine(new int[]{10})).isEqualTo(0);
15+
}
16+
}

0 commit comments

Comments
 (0)