[GeeksForGeeks] Longest Bitonic Subsequence

Given an array arr[0.....n-1] containing n positive integers, find the length of the longest bitonic subsequence. 

A subsequence of arr[] is called Bitonic if it is first increasing, then decreasing.

 

Analysis: 

This problem is a variation of the standard Longest Increasing Subsequence(LIS) problem.  In the standard LIS

problem, we use dynamic programming and create a 1D array lis[i], lis[i] is the length of the longest increasing subsequence 

that ends with arr[i]. 

 

In this problem, we construct two arrays lis[i] and ids[i] using dynamic programming.

lis[i] stores the length of the longest increasing subsequence ending with arr[i];

lds[i] stores the length of the longest decreasing subsequence starting from arr[i];

Finally, we need to return the max value of lis[i] + lds[i] - 1, where i is from 0 to n - 1.

 

 1 public class Solution {
 2     public int longestBitonicSubsequence(int[] arr){
 3         if(arr == null || arr.length == 0){
 4             return 0;
 5         }
 6         int[] lis = new int[arr.length];
 7         int[] lds = new int[arr.length];
 8         for(int i = 0; i < arr.length; i++){
 9             lis[i] = 1;
10             lds[i] = 1;
11         }
12         for(int i = 0; i < arr.length; i++){
13             for(int j = 0; j < i; j++){
14                 if(arr[i] > arr[j] && lis[i] < lis[j] + 1){
15                     lis[i] = lis[j] + 1;
16                 }
17             }
18         }
19         for(int i = arr.length - 1; i >= 0; i--){
20             for(int j = arr.length - 1; j > i; j--){
21                 if(arr[i] > arr[j] && lds[i] < lds[j] + 1){
22                     lds[i] = lds[j] + 1;
23                 }
24             }
25         }
26         int max = 0;
27         for(int i = 0; i < arr.length; i++){
28             if(lis[i] + lds[i] - 1 > max){
29                 max = lis[i] + lds[i] - 1;
30             }
31         }
32         return max;
33     }
34 }

 

Related Problems

Longest Increasing Subsequence

 

posted @ 2017-07-20 06:41  Review->Improve  阅读(467)  评论(0编辑  收藏  举报