Close

Maximum increasing sub array

Given an array of numbers, how to find the maximum length of increasing (non-decreasing) continuous sub-sequence?
For example consider the array [7, 9, 1, 3, 5, 8, 2], the maximum length is 4. Similarly for [23, 10, 18, 18, 6], it is 3.
This is a straight forward implementation problem (appeared on Codeforces). Following is an implementation of O(n) algorithm.

#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int i;
int prev = 0;
int max_len = 0, len = 0;
for( i = 0; i < n; i++ )
{
int num;
cin >> num;
if( num >= prev )
len++;
else
len = 1;
max_len = max(len, max_len);
prev = num;
}
cout << max_len << endl;
return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *