1. All Peaks Enumeration with Subsequence Search
Intuition
For each index i, recursively search for the longest increasing subsequence ending at i and longest decreasing starting at i.
Algorithm
- For each index
ifrom 0 to n-1: - Find max increasing subsequence ending at i.
- Find max decreasing subsequence starting at i.
- Add lengths and subtract 1.
- Return global maximum.
#include <iostream>#include <vector>#include <algorithm> using namespace std; int getLIS(int idx, const vector<int>& nums) { int maxLen = 1; for (int j = 0; j < idx; j++) { if (nums[j] < nums[idx]) { maxLen = max(maxLen, 1 + getLIS(j, nums)); } } return maxLen;} int getLDS(int idx, const vector<int>& nums) { int maxLen = 1; for (int j = idx + 1; j < (int)nums.size(); j++) { if (nums[j] < nums[idx]) { maxLen = max(maxLen, 1 + getLDS(j, nums)); } } return maxLen;} int longestBitonicRec(const vector<int>& nums) { int n = nums.size(); int ans = 0; for (int i = 0; i < n; i++) { ans = max(ans, getLIS(i, nums) + getLDS(i, nums) - 1); } return ans;} int main() { vector<int> nums = {1, 2, 5, 3, 2}; cout << "Longest Bitonic (Recursive): " << longestBitonicRec(nums) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(n * 2^n) - Space complexity:
O(n) call stack