0

i have a list which have some values in it

for (int i = 0; i < InputNumbers.Length; i++)
        {
            InputNumbers[i] = Convert.ToInt32(Console.ReadLine());
            LongestSequence.Add(InputNumbers[i]);
        }
        for (int i = 0; i < InputNumbers.Length; i++)
        {
            if (i > 0)
            {
                if (LongestSequence[i] < LongestSequence[i - 1])
                {
                    LongestSequence.Remove(LongestSequence[i]);
                    LongestSequence.Insert(i, null);
                }
            }
        }

As you can see im adding all the values from my array InputNumbers to the list LongestSequence and after this is done im removing some of those values and inserting "null" at the replaced value index. So this creates something like border :

null
1  
2
null

i want to know the length of the values between those 2 null's.In this case it's 2

  • if the input is 1 2 3 0 the null will be at the start and will replace the zero because 0 is lower than 3 and im looking for the longest non decreasing sequence
kopelence
  • 173
  • 1
  • 2
  • 9

1 Answers1

0

It looks like XY problem. You need to find the longest non decreasing sequence, and you have found a terrible way to do this, and now you want us to help you with it. It is better to ask directly to help with the longest non-decreasing sequence. There is no need in settings nulls and then trying to find values between them.

You can simply do the following:

List<int> current = new List<int> { Int32.MaxValue };
int[] best = new int[0];

int n = int.Parse(Console.ReadLine());   

for (int i = 0; i < n; i++)
{
    var read = int.Parse(Console.ReadLine());

    if (read < current[current.Count - 1])
    {
        if (current.Count > best.Length) best = current.ToArray();
        current.Clear();
    }

    current.Add(read);
}

if (current.Count > best.Length) best = current.ToArray();

// Here, "best" stores the best result

It looks more clear, transparent and readable.
However, I strongly believe that there are many even shorter and more elegant solutions.

Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101