
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Number of Longest Increasing Subsequence in C++
Suppose we have one unsorted array of integers. we have to find the number of longest increasing subsequence, so if the input is like [1, 3, 5, 4, 7], then the output will be 2, as increasing subsequence are [1,3,5,7] and [1, 3, 4, 7]
To solve this, we will follow these steps −
- n := size of the num array, create two arrays len and cnt of size n, and fill them with value 1.
- lis := 1
- for i in range 1 to n
- for j in range 0 to i – 1
- if nums[i] > nums[j], then
- if len[j] + 1 > len[i], then len[i] := len[j] + 1, and cnt[i] := cnt[j]
- otherwise when len[j] + 1 = len[j], then cnt[i] := cnt[i] + cnt[j]
- lis := max of lis and len[j]
- if nums[i] > nums[j], then
- for j in range 0 to i – 1
- ans := 0
- for i in range 0 to n – 1
- if len[i] = lis, then ans := ans + cnt[j]
- return ans
Example(C++)
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: int findNumberOfLIS(vector<int>& nums) { int n = nums.size(); vector <int> len(n, 1), cnt(n, 1); int lis = 1; for(int i = 1; i < n; i++){ for(int j = 0; j < i; j++){ if(nums[i] > nums[j]){ if(len[j] + 1 > len[i]){ len[i] = len[j] + 1; cnt[i] = cnt[j]; } else if(len[j] + 1 == len[i]){ cnt[i] += cnt[j]; } } lis = max(lis, len[i]); } } int ans = 0; for(int i = 0; i < n; i++){ if(len[i] == lis)ans += cnt[i]; } return ans; } }; main(){ Solution ob; vector<int> v = {1,3,5,4,7}; cout << (ob.findNumberOfLIS(v)); }
Input
[1,3,5,4,7]
Output
2
- Related Articles
- Longest Increasing Subsequence
- Longest Increasing Subsequence in Python
- Longest Continuous Increasing Subsequence in C++
- Java Program for Longest Increasing Subsequence
- Program to find length of longest increasing subsequence in Python
- Program to find length of longest circular increasing subsequence in python
- C++ Program to Find the Longest Increasing Subsequence of a Given Sequence
- Total number of longest increasing sequences in JavaScript
- Program to find length of longest increasing subsequence with at least k odd values in Python
- Longest Common Subsequence
- Longest Bitonic Subsequence
- Longest Palindromic Subsequence
- Increasing Triplet Subsequence in Python
- Longest Common Subsequence in C++
- Longest Harmonious Subsequence in C++

Advertisements