Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how can i get the longest sequence of increasing numbers from a vector in c++?

I have this sequence of numbers stored in a vector: 4 7 2 6 5 1 3.
In this case, the longest sequence will be: 1,3,4,7. That’s 4 numbers.
I only need to get the value of the longest increasing sequence(in this case 4).

I have this code:


using namespace std;
ifstream f("roboti2.in");
ofstream g("roboti2.out");

int main()
{
    int cerinta, n;
    int v[10000];
    f>>cerinta>>n;

    if(cerinta==1)
    {
        int l=1;
        int maxl = 1;
        for(int i=0; i<=n;i++)
        {
            f>>v[i];
        }
        for(int i=1; i<=n; i++)
        {
            if(v[i] > v[i-1])
            {
               l++;
               if (l > maxl)
               {
                   maxl = l;
               }

            }
            else
            {
               l=1;
            }
        }
        g<<maxl;

    }
    return 0;
}

But it shows that it’s 2. It does not take the numbers at the end(1, 3) and 4,7.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks!

>Solution :

To consider this kind of warp from the end to the beginning, an easy way is duplicating the array after the original array and also check the second array.

for(int i=0; i<=n;i++)
{
    f>>v[i];
}
// add this to duplicate the array
// (assuming v[0] .. v[n] is what to consider
for(int i=0; i<=n; i++)
{
    v[n+i+1] = v[i];
}
n += n + 1;

The size of array v should be increased to store the duplicate part if needed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading