DP #34. Longest Bitonic Sequence - mbhushan/dynpro GitHub Wiki
(34). Longest Bitonic Sequence.
Given an array arr[0 … n-1] containing n positive integers, a subsequence
of arr[] is called Bitonic if it is first increasing, then decreasing.
Write a function that takes an array as argument and returns the length of
the longest bitonic subsequence.
A sequence, sorted in increasing order is considered Bitonic with the
decreasing part as empty. Similarly, decreasing order sequence is considered
Bitonic with the increasing part as empty.
Examples:
Input arr[] = {1, 11, 2, 10, 4, 5, 2, 1};
Output: 6 (A Longest Bitonic Subsequence of length 6 is 1, 2, 10, 4, 2, 1)
Input arr[] = {12, 11, 40, 5, 3, 1}
Output: 5 (A Longest Bitonic Subsequence of length 5 is 12, 11, 5, 3, 1)
Input arr[] = {80, 60, 30, 40, 20, 10}
Output: 5 (A Longest Bitonic Subsequence of length 5 is 80, 60, 30, 20, 10)
Approach:
a. Find the max increasing subsequence from left to right.
b. find the max increasing subsequence from right to left.
c. max(left + right - 1) would be the ans.
//we are doing -1 because one element is counted twice - at intersection point of left & right.
Formula for max increasing subsequence.
if (A[i] < A[j]) {
T[j] = Max (T[j], 1 + T[i])
}
//j goes from i+1 to A.length;
index |
0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
|
1 |
11 |
2 |
10 |
4 |
5 |
2 |
1 |
Left to Right |
1 |
2 |
2 |
3 |
3 |
4 |
2 |
1 |
Right to Left |
1 |
5 |
2 |
4 |
3 |
3 |
2 |
1 |
bitonic seq |
1 |
6 |
3 |
6 |
5 |
6 |
3 |
1 |
|
|
|
|
|
|
|
|
|
max bitonic seq |
6 |
|
|
|
|
|
|
|
Bitonic Sequence
- Time Complexity: O(n^2)
- Space Complexity: O(n)