Reducing the complexity of an algorithm

Greetings everyone. I have this algortihm:
int x[100001],n,j,k,i;
int maxi=0;
for (i=1; i<n; i++)
for (j=i+1; j<=n; j++)
{ bool ok=true;
for (k=i+1; k<=j; k++)
{ if (x[i]<x[i-1])
ok=false;
}
if (ok == true)
if (j-i+1 > maxi)
maxi = j-i+1;
}
cout << maxi;
How can I reduce the complexity, which is obviously O(n^3) to something lower? Many thanks in advance.
What is the code supposed to be doing?

Here's your code in readable form (see code tags: http://www.cplusplus.com/forum/articles/16853/).
1
2
3
4
5
6
7
8
9
10
11
12
int x[100001], n, j, k, i;
int maxi = 0;
for (i = 1; i < n; i++)
    for (j = i + 1; j <= n; j++) {
        bool ok = true;
        for (k = i + 1; k <= j; k++)
            if (x[i] < x[i - 1])
                ok = false;
        if (ok && j - i + 1 > maxi) 
            maxi = j - i + 1;
    }
cout << maxi;


n is being used uninitialized (in the snippet you posted, at least).
It should look to Find the Longest Ascending Subsequence
Topic archived. No new replies allowed.