Problem: Find out the longest continuous sub-sequence.
Analysis:
This is a canonical solution. Runing from the ledt side of the given sequence, if the i+1th element is bigger or equal to the ith one, add to a temporary vector. Otherwise, the i+1th element will not increase the length of the current stored sub-sequence. Then, compare the temporary vector with the returned vector, replace the returned vector with the temporary one.
The time complexity is O(n).
Solutions:
C++:
vector<int> longest_monotonous_sequence(int seq[], int n, bool isIncreased = true)
{
vector<int> lms;
if(n == 0)
return lms;
vector<int> temp_mon_seq;
for(int i = 0; i < n; ++i) {
if(temp_mon_seq.empty())
temp_mon_seq.push_back(seq[i]);
else {
if(isIncreased) {
if(seq[i] >= *(temp_mon_seq.end() - 1))
temp_mon_seq.push_back(seq[i]);
else {
if(temp_mon_seq.size() > lms.size())
lms = temp_mon_seq;
temp_mon_seq.clear();
}
} else {
if(seq[i] <= *(temp_mon_seq.end() - 1))
temp_mon_seq.push_back(seq[i]);
else {
if(temp_mon_seq.size() > lms.size())
lms = temp_mon_seq;
temp_mon_seq.clear();
}
}
}
}
if(temp_mon_seq.size() > lms.size())
lms = temp_mon_seq;
return lms;
}