Last active
April 28, 2016 20:53
-
-
Save dgodfrey206/577fedf1483315ec5f9caf05f78ea784 to your computer and use it in GitHub Desktop.
Calculating the length of the longest contiguous subsequence
This file contains hidden or 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
#include <iostream> | |
#include <vector> | |
using std::max; | |
// Let A be an array of length N | |
// Let M(i) be the largest contiguous subsequence ending at index i | |
// M(0) = 1 | |
// M(i) = max(M(i),M(j)+1) for j<i and A[j]<=A[i] | |
int maxSubArray(int A[], int N) { | |
if (N==0)return 0; | |
std::vector<int> M(N); | |
int best = M[0] = 1; | |
for (int i = 1; i < N; ++i) { | |
if (A[i-1]<=A[i]) M[i]=max(M[i],M[i-1]+1); | |
best = max(best,M[i]); | |
} | |
return best; | |
} | |
template<class T,std::size_t N> | |
constexpr std::size_t size(T(&)[N]){return N;} | |
int main() { | |
int arr[] = {1,-2,3,9,10,39,-2,2,5}; | |
std::cout << maxSubArray(arr,size(arr)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment