forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMaxSpan.java
45 lines (41 loc) · 1.37 KB
/
MaxSpan.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.rampatra.arrays;
import com.sun.tools.javac.util.Assert;
/**
* Consider the leftmost and rightmost appearances of some value in an array. We'll say that the "span" is the
* number of elements between the two inclusive. A single value has a span of 1. Returns the largest span found
* in the given array.
* <p>
* Examples:
* maxSpan([1, 2, 1, 1, 3]) → 4
* maxSpan([1, 4, 2, 1, 4, 1, 4]) → 6
* maxSpan([1, 4, 2, 1, 4, 4, 4]) → 6
* <p>
* Level: Easy
*
* @author rampatra
* @link https://codingbat.com/prob/p189576
* @since 2019-01-23
*/
public class MaxSpan {
public static int maxSpan(int[] nums) {
if (nums.length == 0) return 0;
int largestSpan = 1;
for (int i = 0; i < nums.length; i++) {
for (int j = nums.length - 1; j > i; j--) {
if (nums[i] == nums[j]) {
if (j - i + 1 > largestSpan) {
largestSpan = j - i + 1;
}
}
}
}
return largestSpan;
}
public static void main(String[] args) {
Assert.check(maxSpan(new int[]{1, 2, 1, 1, 3}) == 4);
Assert.check(maxSpan(new int[]{1, 4, 2, 1, 4, 1, 4}) == 6);
Assert.check(maxSpan(new int[]{1, 4, 2, 1, 4, 4, 4}) == 6);
Assert.check(maxSpan(new int[]{1}) == 1);
Assert.check(maxSpan(new int[]{}) == 0);
}
}