Longest Decreasing Subsequence
Last Updated :
28 Feb, 2023
Given an array of N integers, find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in strictly decreasing order.
Examples:
Input: arr[] = [15, 27, 14, 38, 63, 55, 46, 65, 85]
Output: 3
Explanation: The longest decreasing subsequence is {63, 55, 46}
Input: arr[] = {50, 3, 10, 7, 40, 80}
Output: 3
Explanation: The longest decreasing subsequence is {50, 10, 7}
The problem can be solved using Dynamic Programming
Optimal Substructure:
Let arr[0...n-1] be the input array and lds[i] be the length of the LDS ending at index i such that arr[i] is the last element of the LDS.
Then, lds[i] can be recursively written as:
lds[i] = 1 + max(lds[j]) where i > j > 0 and arr[j] > arr[i] or
lds[i] = 1, if no such j exists.
To find the LDS for a given array, we need to return max(lds[i]) where n > i > 0.
C++
// CPP program to find the length of the
// longest decreasing subsequence
#include <bits/stdc++.h>
using namespace std;
// Function that returns the length
// of the longest decreasing subsequence
int lds(int arr[], int n)
{
int lds[n];
int i, j, max = 0;
// Initialize LDS with 1 for all index
// The minimum LDS starting with any
// element is always 1
for (i = 0; i < n; i++)
lds[i] = 1;
// Compute LDS from every index
// in bottom up manner
for (i = 1; i < n; i++)
for (j = 0; j < i; j++)
if (arr[i] < arr[j] && lds[i] < lds[j] + 1)
lds[i] = lds[j] + 1;
// Select the maximum
// of all the LDS values
for (i = 0; i < n; i++)
if (max < lds[i])
max = lds[i];
// returns the length of the LDS
return max;
}
// Driver Code
int main()
{
int arr[] = { 15, 27, 14, 38, 63, 55, 46, 65, 85 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Length of LDS is " << lds(arr, n);
return 0;
}
Java
// Java program to find the
// length of the longest
// decreasing subsequence
import java.io.*;
class GFG
{
// Function that returns the
// length of the longest
// decreasing subsequence
static int lds(int arr[], int n)
{
int lds[] = new int[n];
int i, j, max = 0;
// Initialize LDS with 1
// for all index. The minimum
// LDS starting with any
// element is always 1
for (i = 0; i < n; i++)
lds[i] = 1;
// Compute LDS from every
// index in bottom up manner
for (i = 1; i < n; i++)
for (j = 0; j < i; j++)
if (arr[i] < arr[j] &&
lds[i] < lds[j] + 1)
lds[i] = lds[j] + 1;
// Select the maximum
// of all the LDS values
for (i = 0; i < n; i++)
if (max < lds[i])
max = lds[i];
// returns the length
// of the LDS
return max;
}
// Driver Code
public static void main (String[] args)
{
int arr[] = { 15, 27, 14, 38,
63, 55, 46, 65, 85 };
int n = arr.length;
System.out.print("Length of LDS is " +
lds(arr, n));
}
}
// This code is contributed by anuj_67.
Python 3
# Python 3 program to find the length of
# the longest decreasing subsequence
# Function that returns the length
# of the longest decreasing subsequence
def lds(arr, n):
lds = [0] * n
max = 0
# Initialize LDS with 1 for all index
# The minimum LDS starting with any
# element is always 1
for i in range(n):
lds[i] = 1
# Compute LDS from every index
# in bottom up manner
for i in range(1, n):
for j in range(i):
if (arr[i] < arr[j] and
lds[i] < lds[j] + 1):
lds[i] = lds[j] + 1
# Select the maximum
# of all the LDS values
for i in range(n):
if (max < lds[i]):
max = lds[i]
# returns the length of the LDS
return max
# Driver Code
if __name__ == "__main__":
arr = [ 15, 27, 14, 38,
63, 55, 46, 65, 85 ]
n = len(arr)
print("Length of LDS is", lds(arr, n))
# This code is contributed by ita_c
C#
// C# program to find the
// length of the longest
// decreasing subsequence
using System;
class GFG
{
// Function that returns the
// length of the longest
// decreasing subsequence
static int lds(int []arr, int n)
{
int []lds = new int[n];
int i, j, max = 0;
// Initialize LDS with 1
// for all index. The minimum
// LDS starting with any
// element is always 1
for (i = 0; i < n; i++)
lds[i] = 1;
// Compute LDS from every
// index in bottom up manner
for (i = 1; i < n; i++)
for (j = 0; j < i; j++)
if (arr[i] < arr[j] &&
lds[i] < lds[j] + 1)
lds[i] = lds[j] + 1;
// Select the maximum
// of all the LDS values
for (i = 0; i < n; i++)
if (max < lds[i])
max = lds[i];
// returns the length
// of the LDS
return max;
}
// Driver Code
public static void Main ()
{
int []arr = { 15, 27, 14, 38,
63, 55, 46, 65, 85 };
int n = arr.Length;
Console.Write("Length of LDS is " +
lds(arr, n));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP program to find the
// length of the longest
// decreasing subsequence
// Function that returns the
// length of the longest
// decreasing subsequence
function lds($arr, $n)
{
$lds = array();
$i; $j; $max = 0;
// Initialize LDS with 1
// for all index The minimum
// LDS starting with any
// element is always 1
for ($i = 0; $i < $n; $i++)
$lds[$i] = 1;
// Compute LDS from every
// index in bottom up manner
for ($i = 1; $i < $n; $i++)
for ($j = 0; $j < $i; $j++)
if ($arr[$i] < $arr[$j] and
$lds[$i] < $lds[$j] + 1)
{
$lds[$i] = $lds[$j] + 1;
}
// Select the maximum
// of all the LDS values
for ($i = 0; $i < $n; $i++)
if ($max < $lds[$i])
$max = $lds[$i];
// returns the length
// of the LDS
return $max;
}
// Driver Code
$arr = array(15, 27, 14, 38, 63,
55, 46, 65, 85);
$n = count($arr);
echo "Length of LDS is " ,
lds($arr, $n);
// This code is contributed by anuj_67.
?>
JavaScript
<script>
// Javascript program to find the
// length of the longest
// decreasing subsequence
// Function that returns the
// length of the longest
// decreasing subsequence
function lds(arr,n)
{
let lds = new Array(n);
let i, j, max = 0;
// Initialize LDS with 1
// for all index. The minimum
// LDS starting with any
// element is always 1
for (i = 0; i < n; i++)
lds[i] = 1;
// Compute LDS from every
// index in bottom up manner
for (i = 1; i < n; i++)
for (j = 0; j < i; j++)
if (arr[i] < arr[j] &&
lds[i] < lds[j] + 1)
lds[i] = lds[j] + 1;
// Select the maximum
// of all the LDS values
for (i = 0; i < n; i++)
if (max < lds[i])
max = lds[i];
// returns the length
// of the LDS
return max;
}
// Driver Code
let arr=[15, 27, 14, 38,
63, 55, 46, 65, 85 ];
let n = arr.length;
document.write("Length of LDS is " +
lds(arr, n));
// This code is contributed by rag2127
</script>
Output : Length of LDS is 3
Time Complexity: O(n2)
Auxiliary Space: O(n)
Related Article: https://www.geeksforgeeks.org/longest-increasing-subsequence/
Longest Decreasing Subsequence in O(n*log(n)) :
Another approach to finding the Longest Decreasing Subsequence is using the Longest Increasing Subsequence approach in n*log(n) complexity. Here is the link to find the details of the approach with O(n*log(n)) complexity https://www.geeksforgeeks.org/longest-monotonically-increasing-subsequence-size-n-log-n/.
We can observe that the length of the Longest Decreasing Subsequence of any array is same as the length of the Longest Increasing Subsequence of that array if we multiply all elements by -1.
For example:
arr[] = [15, 27, 14, 38, 63, 55, 46, 65, 85]
then the length of longest decreasing subsequence of this array is same as length of longest increasing subsequence of arr[]=[-15, -27, -14, -38, -63, -55, -46, -65, -85]
In both cases the length is 3.
Steps to solve this problem:
1. Check if array is zero than return zero.
2. Declare a vector tail of array size.
3. Declare a variable length=1.
4. Initialize tail[0]=v[0].
5. Iterate through i=1 till size of array:
*Initialize auto b=tail.begin and e=tail.begin+length.
*Initialize auto it to lower bound of v[i].
*Check if it is equal to tail.begin+length than tail[length++]=v[i].
*Else update value at it =v[i].
6. Return length.
Below is the code of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find longest Longest Increasing Subsequence Length
int LongestIncreasingSubsequenceLength(vector<int>& v)
{
if (v.size() == 0) // boundary case
return 0;
vector<int> tail(v.size(), 0);
int length = 1; // always points empty slot in tail
tail[0] = v[0];
for (int i = 1; i < v.size(); i++) {
// Do binary search for the element in
// the range from begin to begin + length
auto b = tail.begin(), e = tail.begin() + length;
auto it = lower_bound(b, e, v[i]);
// If not present change the tail element to v[i]
if (it == tail.begin() + length)
tail[length++] = v[i];
else
*it = v[i];
}
return length;
}
int main()
{
vector<int> v{ 15, 27, 14, 38, 63, 55, 46, 65, 85 };
int n=v.size();
// Making all elements negative as
// Longest Decreasing Subsequence of any array is
// same as longest Increasing Subsequence
// of negative values of that array.
for(int i=0;i<n;i++)
{
v[i]=-1*v[i];
}
cout
<< "Length of Longest Decreasing Subsequence is "
<< LongestIncreasingSubsequenceLength(v);
return 0;
}
// This code is contributed by Pushpesh Raj.
Java
// Java code for above approach
import java.io.*;
import java.lang.Math;
import java.util.*;
class LIS {
// Function to find longest Longest Increasing Subsequence Length
static int LongestIncreasingSubsequenceLength(int v[])
{
if (v.length == 0) // boundary case
return 0;
int[] tail = new int[v.length];
int length = 1; // always points empty slot in tail
tail[0] = v[0];
for (int i = 1; i < v.length; i++) {
if (v[i] > tail[length - 1]) {
// v[i] extends the largest subsequence
tail[length++] = v[i];
}
else {
// v[i] will extend a subsequence and
// discard older subsequence
// find the largest value just smaller than
// v[i] in tail
// to find that value do binary search for
// the v[i] in the range from begin to 0 +
// length
int idx = Arrays.binarySearch(
tail, 0, length - 1, v[i]);
// binarySearch in java returns negative
// value if searched element is not found in
// array
// this negative value stores the
// appropriate place where the element is
// supposed to be stored
if (idx < 0)
idx = -1 * idx - 1;
// replacing the existing subsequence with
// new end value
tail[idx] = v[i];
}
}
return length;
}
// Driver program to test above function
public static void main(String[] args)
{
int v[] = { 2, 5, 3, 7, 11, 8, 10, 13, 6 };
int n=v.length;
// Making all elements negative as
// Longest Decreasing Subsequence of any array is
// same as longest Increasing Subsequence
// of negative values of that array.
for(int i=0;i<n;i++)
{
v[i]=-1*v[i];
}
System.out.println(
"Length of Longest Decreasing Subsequence is "
+ LongestIncreasingSubsequenceLength(v));
}
}
// This code is contributed by Aman Kumar
Python3
from bisect import bisect_left
# Function to find longest Longest Increasing Subsequence Length
def LongestIncreasingSubsequenceLength(v):
n = len(v)
if n == 0: # boundary case
return 0
tail = [0] * n # vector to store the tail elements
length = 1 # always points empty slot in tail
tail[0] = v[0]
for i in range(1, n):
# Do binary search for the element in the range from begin to begin + length
j = bisect_left(tail, v[i], 0, length)
# If not present change the tail element to v[i]
if j == length:
tail[length] = v[i]
length += 1
else:
tail[j] = v[i]
return length
v = [15, 27, 14, 38, 63, 55, 46, 65, 85]
v = [-x for x in v] # Making all elements negative
print("Length of Longest Decreasing Subsequence is", LongestIncreasingSubsequenceLength(v))
# This code is contributed by unstoppablepandu.
C#
using System;
using System.Linq;
class LIS {
// Function to find longest Longest Increasing
// Subsequence Length
static int LongestIncreasingSubsequenceLength(int[] v)
{
if (v.Length == 0) // boundary case
return 0;
int[] tail = new int[v.Length];
int length = 1; // always points empty slot in tail
tail[0] = v[0];
for (int i = 1; i < v.Length; i++) {
if (v[i] > tail[length - 1]) {
// v[i] extends the largest subsequence
tail[length++] = v[i];
}
else {
// v[i] will extend a subsequence and
// discard older subsequence
// find the largest value just smaller than
// v[i] in tail
// to find that value do binary search for
// the v[i] in the range from begin to 0 +
// length
int idx = Array.BinarySearch(
tail, 0, length - 1, v[i]);
// binarySearch in C# returns negative
// value if searched element is not found in
// array
// this negative value stores the
// appropriate place where the element is
// supposed to be stored
if (idx < 0)
idx = ~idx;
// replacing the existing subsequence with
// new end value
tail[idx] = v[i];
}
}
return length;
}
// Driver program to test above function
public static void Main(string[] args)
{
int[] v = { 2, 5, 3, 7, 11, 8, 10, 13, 6 };
int n = v.Length;
// Making all elements negative as
// Longest Decreasing Subsequence of any array is
// same as longest Increasing Subsequence
// of negative values of that array.
for (int i = 0; i < n; i++) {
v[i] = -1 * v[i];
}
Console.WriteLine(
"Length of Longest Decreasing Subsequence is "
+ LongestIncreasingSubsequenceLength(v));
}
}
JavaScript
//JavaScript program to implement above approach.
function LongestIncreasingSubsequenceLength(v) {
if (v.length === 0) { // boundary case
return 0;
}
const tail = new Array(v.length).fill(0);
let length = 1; // always points empty slot in tail
tail[0] = v[0];
for (let i = 1; i < v.length; i++) {
// Do binary search for the element in
// the range from begin to begin + length
let b = 0, e = length;
let mid;
while (b < e) {
mid = Math.floor((b + e) / 2);
if (tail[mid] < v[i]) {
b = mid + 1;
} else {
e = mid;
}
}
// If not present change the tail element to v[i]
if (b === length) {
tail[length++] = v[i];
} else {
tail[b] = v[i];
}
}
return length;
}
let v = [15, 27, 14, 38, 63, 55, 46, 65, 85];
let n = v.length;
// Making all elements negative as
// Longest Decreasing Subsequence of any array is
// same as longest Increasing Subsequence
// of negative values of that array.
for (let i = 0; i < n; i++) {
v[i] = -v[i];
}
console.log("Length of Longest Decreasing Subsequence is " +
LongestIncreasingSubsequenceLength(v));
OutputLength of Longest Decreasing Subsequence is 3
Time Complexity: O(n*logn)
Auxiliary Space: O(n)
Similar Reads
Longest Increasing Subsequence (LIS) Given an array arr[] of size n, the task is to find the length of the Longest Increasing Subsequence (LIS) i.e., the longest possible subsequence in which the elements of the subsequence are sorted in increasing order.Examples: Input: arr[] = [3, 10, 2, 1, 20]Output: 3Explanation: The longest increa
14 min read
Longest alternating subsequence A sequence {X1, X2, .. Xn} is an alternating sequence if its elements satisfy one of the following relations : X1 < X2 > X3 < X4 > X5 < â¦. xn or X1 > X2 < X3 > X4 < X5 > â¦. xn Examples: Input: arr[] = {1, 5, 4}Output: 3Explanation: The whole arrays is of the form x1
15+ min read
Longest Increasing Odd Even Subsequence Given an array of size n. The problem is to find the length of the subsequence in the given array such that all the elements of the subsequence are sorted in increasing order and also they are alternately odd and even. Note that the subsequence could start either with the odd number or with the even
8 min read
Longest dividing subsequence You are given an array A of size N. Your task is to find the length of largest dividing sub sequence.A dividing sequence is a sequence a1, a2, â¦, aN where ai divides aj whenever i < j. For example, 3, 15, 60, 720 is a dividing sequence. input- The first line of each test case is N, where N is the
5 min read
Longest Increasing consecutive subsequence Given N elements, write a program that prints the length of the longest increasing consecutive subsequence. Examples: Input : a[] = {3, 10, 3, 11, 4, 5, 6, 7, 8, 12} Output : 6 Explanation: 3, 4, 5, 6, 7, 8 is the longest increasing subsequence whose adjacent element differs by one. Input : a[] = {6
10 min read
Longest Increasing Subsequence using BIT Given an array arr, the task is to find the length of The Longest Increasing Sequence using Binary Indexed Tree (BIT) Examples: Input: arr = {6, 5, 1, 3, 2, 4, 8, 7} Output: 4 Explanation: The possible subsequences are {1 2 4 7}, {1 2 4 8}, {1 3 4 8}, {1 3 4 7} Now insert the elements one by one fro
13 min read
Number of Longest Increasing Subsequences Given an array arr[] of size n, the task is to count the number of longest increasing subsequences present in the given array.Examples:Input: arr[] = [2, 2, 2, 2, 2]Output: 5Explanation: The length of the longest increasing subsequence is 1, i.e. {2}. Therefore, count of longest increasing subsequen
15+ min read
Longest Increasing Subsequence Size (N log N) Given an array arr[] of size N, the task is to find the length of the Longest Increasing Subsequence (LIS) i.e., the longest possible subsequence in which the elements of the subsequence are sorted in increasing order, in O(N log N).Examples: Input: arr[] = {3, 10, 2, 1, 20}Output: 3Explanation: The
9 min read
Longest Bitonic Subsequence Given an array arr[] containing n positive integers, a subsequence of numbers is called bitonic if it is first strictly increasing, then strictly decreasing. The task is to find the length of the longest bitonic subsequence. Note: Only strictly increasing (no decreasing part) or a strictly decreasin
15+ min read
Printing Longest Increasing Subsequence (LIS) Given a sequence of numbers, the task is to find and print the Longest Increasing Subsequence (LIS), the longest subsequence where each element is strictly greater than the previous one. If multiple LIS of the same maximum length exist, we must select the one that appears first based on the lexicogr
15+ min read