-
Notifications
You must be signed in to change notification settings - Fork 1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #167 from nikhilpuria/master
Adding Longest Increasing Subsequence DP algorithm in C++
- Loading branch information
Showing
1 changed file
with
45 additions
and
0 deletions.
There are no files selected for viewing
45 changes: 45 additions & 0 deletions
45
Dynamic Programming/Longest Increasing Subsequence/cpp/longest_increasing_subsequence.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
/** | ||
* The program finds the length of the Longest subsequence (may not be | ||
* continuous) such that the subsequence is in increasing order | ||
*/ | ||
#include <bits/stdc++.h> | ||
using namespace std; | ||
|
||
|
||
|
||
int findMax(int arr[], int length) { | ||
int max = 0; | ||
for (int i = 0; i < length; i++) { | ||
if (max < arr[i]) { | ||
max = arr[i]; | ||
} | ||
} | ||
return max; | ||
} | ||
|
||
int findLongestIncSubLength(int arr[],int length) { | ||
int dp[length]; | ||
int i, j, max = 0; | ||
|
||
// Initialize Longest Increasing Subsequence values | ||
for (i = 0; i < length; i++) { | ||
dp[i] = 1; | ||
} | ||
|
||
for (i = 1; i < length; i++) { | ||
for (j = 0; j < i; j++) { | ||
if (arr[i] > arr[j] && dp[i] < dp[j] + 1) { | ||
dp[i] = dp[j] + 1; | ||
} | ||
} | ||
} | ||
max = findMax(dp, length); | ||
return max; | ||
} | ||
|
||
int main() { | ||
int arr[] = { 1, 4, 2, 10, 8 }; | ||
int lisLength = findLongestIncSubLength(arr,5); | ||
cout << "Longest Increasing Subsequence Length is : " << lisLength << endl; | ||
|
||
} |