-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSolution.java
70 lines (52 loc) · 1.97 KB
/
Solution.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.util.Arrays;
public class Solution {
private static void incrementIfEquals(int i, int[] array, int[] repeatedCount) {
if (i == 0 || array[i] != array[i - 1]) {
repeatedCount[i] = 1;
return;
}
repeatedCount[i] = repeatedCount[i - 1] + 1;
}
private static int countSequence(int startIndex, int[] array, int[] repeatedCount) {
int i = startIndex;
Integer firstNumber = null;
Integer secondNumber = null;
while (i < array.length) {
if (firstNumber == null) {
firstNumber = array[i];
incrementIfEquals(i++, array, repeatedCount);
continue;
}
if (secondNumber == null) {
secondNumber = array[i];
incrementIfEquals(i++, array, repeatedCount);
continue;
}
if (array[i] != firstNumber && array[i] != secondNumber)
return i;
i++;
}
return i;
}
public static int solve(int[] array) {
int currentIndex = 0;
int maxLength = 0;
int[] repeatedNumberCount = new int[array.length];
while (currentIndex < array.length - 1) {
int stopIndex = countSequence(currentIndex, array, repeatedNumberCount);
maxLength = Math.max(maxLength, stopIndex - currentIndex + repeatedNumberCount[currentIndex] - 1);
currentIndex = stopIndex - 1;
}
return maxLength;
}
public static void main(String[] args) {
int[] array = { 1, 3, 5, 3, 1, 3, 1, 5 };
int[] array2 = { 1, 3, 5, 5, 5, 5, 5, 5, 3, 1, 3, 1, 5 };
int[] array3 = { 1, 3, 3, 5, 5, 5, 5, 5, 5, 3, 1, 3, 1, 5 };
int[] array4 = { 1, 1, 2, 2 };
System.out.println(solve(array)); // 4
System.out.println(solve(array2)); // 8
System.out.println(solve(array3)); // 9
System.out.println(solve(array4)); // 4
}
}