Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitdc8114c

Browse files
committed
Add longest increasing subsequence
1 parent0aee19d commitdc8114c

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
importjava.util.Scanner;
2+
3+
/**
4+
*
5+
* @author Afrizal Fikri (https://github.com/icalF)
6+
*
7+
*/
8+
publicclassLongestIncreasingSubsequence {
9+
publicstaticvoidmain(String[]args)throwsException {
10+
11+
Scannersc =newScanner(System.in);
12+
intn =sc.nextInt();
13+
14+
intar[] =newint[n];
15+
for (inti =0;i <n;i++) {
16+
ar[i] =sc.nextInt();
17+
}
18+
19+
System.out.println(LIS(ar));
20+
}
21+
22+
privatestaticintupperBound(int[]ar,intl,intr,intkey) {
23+
while (l <r-1) {
24+
intm = (l +r) /2;
25+
if (ar[m] >=key)
26+
r =m;
27+
else
28+
l =m;
29+
}
30+
31+
returnr;
32+
}
33+
34+
publicstaticintLIS(int[]array) {
35+
intN =array.length;
36+
if (N ==0)
37+
return0;
38+
39+
int[]tail =newint[N];
40+
intlength =1;// always points empty slot in tail
41+
42+
tail[0] =array[0];
43+
for (inti =1;i <N;i++) {
44+
45+
// new smallest value
46+
if (array[i] <tail[0])
47+
tail[0] =array[i];
48+
49+
// array[i] extends largest subsequence
50+
elseif (array[i] >tail[length-1])
51+
tail[length++] =array[i];
52+
53+
// array[i] will become end candidate of an existing subsequence or
54+
// Throw away larger elements in all LIS, to make room for upcoming grater elements than array[i]
55+
// (and also, array[i] would have already appeared in one of LIS, identify the location and replace it)
56+
else
57+
tail[upperBound(tail, -1,length-1,array[i])] =array[i];
58+
}
59+
60+
returnlength;
61+
}
62+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp