-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWavioSequence.java
75 lines (70 loc) · 1.89 KB
/
WavioSequence.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
71
72
73
74
75
/** #dynamic-programming #lis */
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
class WavioSequence {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()) {
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
// caculate LIS
int[] resultLeft = new int[n];
Arrays.fill(resultLeft, 1);
LIS(arr, resultLeft);
// LIS with reverse Array
int[] resultRight = new int[n];
Arrays.fill(resultRight, 1);
int[] reverseArr = new int[n];
for (int i = 0; i < n; i++) {
reverseArr[i] = arr[n - 1 - i];
}
LIS(reverseArr, resultRight);
// result
int result = 0, cnt;
for (int i = 0; i < n; i++) {
cnt = Math.min(resultLeft[i], resultRight[n - 1 - i]);
if (result < 2 * cnt - 1) {
result = 2 * cnt - 1;
}
}
System.out.println(result);
}
}
public static void LIS(int[] arr, int[] resultArr) {
int len = 1;
ArrayList<Integer> result = new ArrayList<>();
result.add(0);
for (int i = 1; i < arr.length; i++) {
if (arr[i] <= arr[result.get(0)]) {
result.set(0, i);
} else if (arr[i] > arr[result.get(len - 1)]) {
result.add(i);
len++;
resultArr[i] = len;
} else {
int pos = lowerBound(arr, result, len, arr[i]);
resultArr[i] = pos;
result.set(pos, i);
}
}
}
public static int lowerBound(int[] arr, ArrayList<Integer> result, int n, int v) {
int pos = n;
int left = 0, right = n, mid, idx;
while (left < right) {
mid = left + (right - left) / 2;
idx = result.get(mid);
if (arr[idx] >= v) {
pos = mid;
right = mid;
} else {
left = mid + 1;
}
}
return pos;
}
}