Open In App

Maximize count of Decreasing Consecutive Subsequences from an Array

Last Updated : 29 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] consisting of N integers, the task is to find the maximum count of decreasing subsequences possible from an array that satisfies the following conditions: 

  • Each subsequence is in its longest possible form.
  • The difference between adjacent elements of the subsequence is always 1.

Examples: 

Input: arr[] = {2, 1, 5, 4, 3} 
Output:
Explanation: 
Possible decreasing subsequences are { 5, 4, 3 } and { 2, 1 }.
Input: arr[] = {4, 5, 2, 1, 4} 
Output:
Explanation: 
Possible decreasing subsequences are { 4 }, { 5, 4} and { 2, 1}. 

Approach: 
The idea is to use a HashMap to solve the problem. Follow the steps below: 

  • Maintain a HashMap to store the count of subsequences possible for an array element and maxSubsequences to count the total number of possible subsequences.
  • Traverse the array, and for each element arr[i], check if any subsequence exists which can have arr[i] as the next element, by the count assigned to arr[i] in the HashMap.
  • If exists, do the following: 
    • Assign arr[i] as the next element of the subsequence.
    • Decrease count assigned to arr[i] in the HashMap, as the number of possible subsequences with arr[i] as the next element has decreased by 1.
    • Similarly, increase count assigned to arr[i] – 1 in the HashMap, as the number of possible subsequences with arr[i] – 1 as the next element has increased by 1.
  • Otherwise, increase maxCount, as a new subsequence is required and repeat the above step to modify the HashMap.
  • After completing the traversal of the array, print the value of maxCount.

C++




// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum number
// number of required subsequences
int maxSubsequences(int arr[], int n)
{
 
    // HashMap to store number of
    // arrows available with
    // height of arrow as key
    unordered_map<int, int> m;
 
    // Stores the maximum count
    // of possible subsequences
    int maxCount = 0;
 
    // Stores the count of
    // possible subsequences
    int count;
 
    for (int i = 0; i < n; i++) {
 
        // Check if i-th element can be
        // part of any of the previous
        // subsequence
        if (m.find(arr[i]) != m.end()) {
 
            // Count of subsequences
            // possible with arr[i] as
            // the next element
            count = m[arr[i]];
 
            // If more than one such
            // subsequence exists
            if (count > 1) {
 
                // Include arr[i] in a subsequence
                m[arr[i]] = count - 1;
            }
 
            // Otherwise
            else
                m.erase(arr[i]);
 
            // Increase count of subsequence possible
            // with arr[i] - 1 as the next element
            if (arr[i] - 1 > 0)
                m[arr[i] - 1] += 1;
        }
        else {
 
            // Start a new subsequence
            maxCount++;
 
            // Increase count of subsequence possible
            // with arr[i] - 1 as the next element
            if (arr[i] - 1 > 0)
                m[arr[i] - 1] += 1;
        }
    }
 
    // Return the answer
    return maxCount;
}
 
// Driver Code
int main()
{
 
    int n = 5;
 
    int arr[] = { 4, 5, 2, 1, 4 };
 
    cout << maxSubsequences(arr, n) << endl;
 
    // This code is contributed by bolliranadheer
}


Java




// Java program to implement
// the above approach
import java.util.*;
   
class GFG {
   
    // Function to find the maximum number
    // number of required subsequences
    static int maxSubsequences(int arr[], int n)
    {
   
        // HashMap to store number of
        // arrows available with
        // height of arrow as key
        HashMap<Integer, Integer> map
            = new HashMap<>();
   
        // Stores the maximum count
        // of possible subsequences
        int maxCount = 0;
   
        // Stores the count of
        // possible subsequences
        int count;
   
        for (int i = 0; i < n; i++)
        {
            // Check if i-th element can be
            // part of any of the previous
            // subsequence
            if (map.containsKey(arr[i]))
            {
                // Count  of subsequences
                // possible with arr[i] as
                // the next element
                count = map.get(arr[i]);
   
                // If more than one such
                // subsequence exists
                if (count > 1)
                {
   
                    // Include arr[i] in a subsequence
                    map.put(arr[i], count - 1);
                }
   
                // Otherwise
                else
                    map.remove(arr[i]);
   
                // Increase count of subsequence possible
                // with arr[i] - 1 as the next element
                if (arr[i] - 1 > 0)
                    map.put(arr[i] - 1,
                    map.getOrDefault(arr[i] - 1, 0) + 1);
            }
            else {
   
                // Start a new subsequence
                maxCount++;
   
                // Increase count of subsequence possible
                // with arr[i] - 1 as the next element
                if (arr[i] - 1 > 0)
                    map.put(arr[i] - 1,
                    map.getOrDefault(arr[i] - 1, 0) + 1);
            }
        }
   
        // Return the answer
        return maxCount;
    }
   
    // Driver Code
    public static void main(String[] args)
    {
        int n = 5;
        int arr[] = { 4, 5, 2, 1, 4 };
        System.out.println(maxSubsequences(arr, n));
    }
}


C#




// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
  
class GFG{
   
// Function to find the maximum number
// number of required subsequences
static int maxSubsequences(int []arr, int n)
{
     
    // Dictionary to store number of
    // arrows available with
    // height of arrow as key
    Dictionary<int,
               int> map = new Dictionary<int,
                                         int>();
                                          
    // Stores the maximum count
    // of possible subsequences
    int maxCount = 0;
 
    // Stores the count of
    // possible subsequences
    int count;
 
    for(int i = 0; i < n; i++)
    {
         
        // Check if i-th element can be
        // part of any of the previous
        // subsequence
        if (map.ContainsKey(arr[i]))
        {
             
            // Count  of subsequences
            // possible with arr[i] as
            // the next element
            count = map[arr[i]];
 
            // If more than one such
            // subsequence exists
            if (count > 1)
            {
                 
                // Include arr[i] in a subsequence
                map.Add(arr[i], count - 1);
            }
 
            // Otherwise
            else
                map.Remove(arr[i]);
 
            // Increase count of subsequence possible
            // with arr[i] - 1 as the next element
            if (arr[i] - 1 > 0)
                if (map.ContainsKey(arr[i] - 1))
                    map[arr[i] - 1]++;
                else
                    map.Add(arr[i] - 1, 1);
        }
        else
        {
             
            // Start a new subsequence
            maxCount++;
 
            // Increase count of subsequence possible
            // with arr[i] - 1 as the next element
            if (arr[i] - 1 > 0)
                if (map.ContainsKey(arr[i] - 1))
                    map[arr[i] - 1]++;
                else
                    map.Add(arr[i] - 1, 1);
        }
    }
 
    // Return the answer
    return maxCount;
}
 
// Driver Code
public static void Main(String[] args)
{
    int n = 5;
    int []arr = { 4, 5, 2, 1, 4 };
     
    Console.WriteLine(maxSubsequences(arr, n));
}
}
 
// This code is contributed by Amit Katiyar


Python3




# Python program to implement
# the above approach
 
from collections import defaultdict
 
# Function to find the maximum number
# number of required subsequences
def maxSubsequences(arr, n)->int:
 
    # Dictionary to store number of
    # arrows available with
    # height of arrow as key
    m = defaultdict(int)
 
    # Stores the maximum count
    # of possible subsequences
    maxCount = 0
 
    # Stores the count
    # of possible subsequences
    count = 0
 
    for i in range(0, n):
 
        # Check if i-th element can be
        # part of any of the previous
        # subsequence
        if arr[i] in m.keys():
 
            # Count of subsequences
            # possible with arr[i] as
            # the next element
            count = m[arr[i]]
 
            # If more than one such
            # subsequence exists
            if count > 1:
 
                # Include arr[i] in a subsequence
                m[arr[i]] = count - 1
 
            # Otherwise
            else:
                m.pop(arr[i])
 
            # Increase count of subsequence possible
            # with arr[i] - 1 as the next element
            if arr[i] - 1 > 0:
                m[arr[i] - 1] += 1
 
        else:
            maxCount += 1
 
            # Increase count of subsequence possible
            # with arr[i] - 1 as the next element
            if arr[i] - 1 > 0:
                m[arr[i] - 1] += 1
 
    # Return the answer
    return maxCount
 
 
# Driver Code
if __name__ == '__main__':
    n = 5
    arr = [4, 5, 2, 1, 4]
    print(maxSubsequences(arr, n))
 
# This code is contributed by Riddhi Jaiswal.


Javascript




<script>
 
// Javascript program to implement
// the above approach
 
// Function to find the maximum number
// number of required subsequences
function maxSubsequences(arr, n)
{
      
    // Dictionary to store number of
    // arrows available with
    // height of arrow as key
    let map = new Map();
                                           
    // Stores the maximum count
    // of possible subsequences
    let maxCount = 0;
  
    // Stores the count of
    // possible subsequences
    let count;
  
    for(let i = 0; i < n; i++)
    {
          
        // Check if i-th element can be
        // part of any of the previous
        // subsequence
        if (map.has(arr[i]))
        {
              
            // Count  of subsequences
            // possible with arr[i] as
            // the next element
            count = map[arr[i]];
  
            // If more than one such
            // subsequence exists
            if (count > 1)
            {
                  
                // Include arr[i] in a subsequence
                map.add(arr[i], count - 1);
            }
  
            // Otherwise
            else
                map.delete(arr[i]);
  
            // Increase count of subsequence possible
            // with arr[i] - 1 as the next element
            if (arr[i] - 1 > 0)
                if (map.has(arr[i] - 1))
                    map[arr[i] - 1]++;
                else
                    map.set(arr[i] - 1, 1);
        }
        else
        {
              
            // Start a new subsequence
            maxCount++;
  
            // Increase count of subsequence possible
            // with arr[i] - 1 as the next element
            if (arr[i] - 1 > 0)
                if (map.has(arr[i] - 1))
                    map[arr[i] - 1]++;
                else
                    map.set(arr[i] - 1, 1);
        }
    }
  
    // Return the answer
    return maxCount;
}
 
// Driver code
 
    let n = 5;
    let arr = [ 4, 5, 2, 1, 4 ];
      
    document.write(maxSubsequences(arr, n));
      
</script>


Output

3

Time Complexity: O(n)
Auxiliary Space: O(n)



Similar Reads

Maximize count of Decreasing Subsequences from the given Array
Given an array arr[], the task is to rearrange the array to generate maximum decreasing subsequences and print the count of the maximum number of subsequences possible such that each array element can be part of a single subsequence and the length of the subsequences needs to be maximized. Example: Input: arr[] = {5, 2, 3, 4} Output: 1 Explanation:
5 min read
Count the number of contiguous increasing and decreasing subsequences in a sequence
For a given distinct integer sequence of size N, the task is to count the number of contiguous increasing subsequence and contiguous decreasing subsequence in this sequence.Examples: Input: arr[] = { 80, 50, 60, 70, 40 } Output: 1 2 Explanation: The only one increasing subsequence is (50, 60, 70) and two decreasing subsequences are (80, 50) and (70
9 min read
Minimum increments of Non-Decreasing Subarrays required to make Array Non-Decreasing
Given an array arr[] consisting of N integers, the task is to find the minimum number of operations required to make the array non-decreasing, where, each operation involves incrementing all elements of a non-decreasing subarray from the given array by 1. Examples: Input: arr[] = {1, 3, 1, 2, 4} Output: 2 Explanation: Operation 1: Incrementing arr[
4 min read
Check if Array can be split into subarrays such that XOR of length of Longest Decreasing Subsequences of those subarrays is 0
Given an array of integers arr[] of size N, the task is to check whether arr[] can be split into different subarrays such that on taking the XOR of lengths of LDS (Longest decreasing subsequences) of all the subarrays is equal to 0. Print 'YES' if it is possible to split else print 'NO'. Examples: Input: arr[] = {1, 0, 3, 4, 5}Output: YESExplanatio
6 min read
Maximize length of longest non-decreasing array possible by the elements present in either ends of the given array
Given an array A[] of size N, the task is to find the maximum length of the longest non-decreasing array that can be generated from the given array by appending elements from either of the ends of the given array to the end of the resultant array and removing the appended element one by one. Examples: Input: A[] = {5, 6, 8, 7} Output:: 4 Explanatio
11 min read
Count Subarrays with strictly decreasing consecutive elements
Given an array arr[] containing integers. The task is to find the number of decreasing subarrays with a difference of 1. Examples: Input: arr[] = {3, 2, 1, 4}Output: 7Explanation: Following are the possible decreasing subarrays with difference 1. [3], [2], [1], [4], [3,2], [2,1], and [3,2,1]Therefore, the answer is 7. Input: arr[] = {5, 4, 3, 2, 1,
7 min read
Print all subsequences in first decreasing then increasing by selecting N/2 elements from [1, N]
Given a positive integer N, the task is to print all the subsequences of the array in such a way that the subsequence is first decreasing then increasing by selecting ceil(N/2) elements from 1 to N. Examples: Input: N = 5Output :(2, 1, 3), (2, 1, 4), (2, 1, 5), (3, 1, 2), (3, 1, 4), (3, 1, 5), (3, 2, 4), (3, 2, 5), (4, 1, 2), (4, 1, 3), (4, 1, 5),
11 min read
Minimum number of strictly decreasing subsequences
Given an array arr[] of size N. The task is to split the array into minimum number of strictly decreasing subsequences. Calculate the minimum number of subsequences we can get by splitting. Examples: Input: N = 4, arr[] = {3, 5, 1, 2}Output: 2Explanation: We can split the array into two subsequences: {3,1} and {5,2} Both are strictly decreasing sub
7 min read
Count minimum number of subsets (or subsequences) with consecutive numbers
Given an array of distinct positive numbers, the task is to calculate the number of subsets (or subsequences) from the array such that each subset contains consecutive numbers. Examples: Input : arr[] = {100, 56, 5, 6, 102, 58, 101, 57, 7, 103, 59}Output : 3{5, 6, 7}, { 56, 57, 58, 59}, {100, 101, 102, 103}are 3 subset in which numbers are consecut
10 min read
Remove minimum elements from array such that no three consecutive element are either increasing or decreasing
Given an array of n distinct positive integers. The task is to find the minimum number of elements to be removed such that no three consecutive elements in the array are either increasing or decreasing. That is, after removal either ai - 1 &gt; ai &lt; ai + 1 or ai - 1 &lt; ai &gt; ai + 1. Examples : Input : arr[] = {5, 2, 3, 6, 1} Output : 1 Given
8 min read
Article Tags :
Practice Tags :