Longest Bitonic Subsequence
Pattern: LIS family
A bitonic subsequence rises strictly, then falls strictly. For each index, find the longest increasing run ending there (from the left) and the longest decreasing run starting there (from the right); the best sum minus 1 is the answer.
The problem
Return the length of the longest subsequence that first strictly increases and then strictly decreases. A purely increasing or decreasing subsequence also counts.
Think first
- What does the peak split the subsequence into?
- How do you get the best rising part ending at each index?
- And the falling part?
Hints
Brute force, and why it fails
Try every subsequence: 2ⁿ.
The key insight
Every bitonic subsequence has a peak, and its two halves are independent LIS problems.
Dry run
[1, 11, 2, 10, 4, 5, 2, 1]. up: 1 2 2 3 3 4 2 1.
Step 1 of 2
The plan
up[i] = LIS ending at i (left to right)
down[i] = decreasing run starting at i (right to left)
return max(up[i] + down[i] - 1)
Complexity
- Time
O(n²)- Space
O(n)
Two LIS passes.
Edge cases
- Sorted: n.
- One value: 1.
- All equal: 1.
I've built my logic, show the code
Java
class Solution {
public int longestBitonicSequence(int[] arr) {
int n = arr.length, best = 0;
int[] up = new int[n], down = new int[n]; // longest increasing run ending at i / decreasing run starting at i
for (int i = 0; i < n; i++) {
up[i] = 1;
for (int j = 0; j < i; j++) if (arr[j] < arr[i]) up[i] = Math.max(up[i], up[j] + 1);
}
for (int i = n - 1; i >= 0; i--) {
down[i] = 1;
for (int j = n - 1; j > i; j--) if (arr[j] < arr[i]) down[i] = Math.max(down[i], down[j] + 1);
}
for (int i = 0; i < n; i++) best = Math.max(best, up[i] + down[i] - 1); // i is the peak, counted once
return best;
}
}C++
class Solution {
public:
int longestBitonicSequence(vector<int>& arr) {
int n = static_cast<int>(arr.size()), best = 0;
vector<int> up(n, 1), down(n, 1); // longest increasing run ending at i / decreasing run starting at i
for (int i = 0; i < n; i++)
for (int j = 0; j < i; j++) if (arr[j] < arr[i]) up[i] = max(up[i], up[j] + 1);
for (int i = n - 1; i >= 0; i--)
for (int j = n - 1; j > i; j--) if (arr[j] < arr[i]) down[i] = max(down[i], down[j] + 1);
for (int i = 0; i < n; i++) best = max(best, up[i] + down[i] - 1); // i is the peak, counted once
return best;
}
};Python
class Solution:
def longestBitonicSequence(self, arr: list[int]) -> int:
n = len(arr)
up, down = [1] * n, [1] * n # longest increasing run ending at i / decreasing run starting at i
for i in range(n):
for j in range(i):
if arr[j] < arr[i]:
up[i] = max(up[i], up[j] + 1)
for i in range(n - 1, -1, -1):
for j in range(i + 1, n):
if arr[j] < arr[i]:
down[i] = max(down[i], down[j] + 1)
return max(u + d - 1 for u, d in zip(up, down)) # i is the peak, counted onceCommon mistakes
- Counting the peak twice.
- Using non-strict comparisons.