Skip to content

Commit 27c7927

Browse files
Longest Bitcoin Subsequence
1 parent 5fb16c2 commit 27c7927

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

Longest Bitonic Subsequence.java

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
class Main
2+
{
3+
// Function to find the longest bitonic subsequence in an array
4+
public static int calculateLBS(int[] nums)
5+
{
6+
int n = nums.length;
7+
8+
// base case
9+
if (n == 0) {
10+
return 0;
11+
}
12+
13+
// `I[i]` store the length of the longest increasing subsequence,
14+
// ending at `nums[i]`
15+
int[] I = new int[n];
16+
17+
// `D[i]` stores the length of the longest decreasing subsequence,
18+
// starting with `nums[i]`
19+
int[] D = new int[n];
20+
21+
I[0] = 1;
22+
for (int i = 1; i < n; i++)
23+
{
24+
for (int j = 0; j < i; j++)
25+
{
26+
if (nums[j] < nums[i] && I[j] > I[i]) {
27+
I[i] = I[j];
28+
}
29+
}
30+
I[i]++;
31+
}
32+
33+
D[n - 1] = 1;
34+
for (int i = n - 2; i >= 0; i--)
35+
{
36+
for (int j = n - 1; j > i; j--)
37+
{
38+
if (nums[j] < nums[i] && D[j] > D[i]) {
39+
D[i] = D[j];
40+
}
41+
}
42+
D[i]++;
43+
}
44+
45+
// consider each element as a peak and calculate LBS
46+
int lbs = 1;
47+
for (int i = 0; i < n; i++) {
48+
lbs = Integer.max(lbs, I[i] + D[i] - 1);
49+
}
50+
51+
return lbs;
52+
}
53+
54+
public static void main(String[] args)
55+
{
56+
int[] nums = { 4, 2, 5, 9, 7, 6, 10, 3, 1 };
57+
58+
System.out.print("The length of the longest bitonic subsequence is " +
59+
calculateLBS(nums));
60+
}
61+
}

0 commit comments

Comments
 (0)