URI 1259 - Increasing and Decreasing Odd Pairs

Asked

Viewed 104 times

1

I’m solving that URI Online Judge challenge.

But my code has had the answer "Time limit exceeded", and I don’t understand exactly why.

Follows code below:

 using System;
using System.Linq;

namespace URI_1259
{
    class Program
    {
        static void Main(string[] args)
        {
            int numero = int.Parse(Console.ReadLine());
            int i;
            int[] arr = new int[numero];
            int[] numeroParCrescente = new int[numero];
            int[] numeroImparDecrescente = new int[numero];


            for (i = 0; i < arr.Length; i++)
            {
                arr[i] = int.Parse(Console.ReadLine());

                numeroParCrescente = arr.Where(x => x % 2 == 0).OrderBy(x => x).ToArray();
                numeroImparDecrescente = arr.Where(x => x % 2 != 0).OrderByDescending(x => x).ToArray();
            }

            foreach(var item in numeroParCrescente)
            {
                Console.WriteLine(item);
            }

            foreach(var item in numeroImparDecrescente)
            {
                Console.WriteLine(item);
            }
        }
    }
}

What is the reason, or some way to optimize?

1 answer

2


It makes no sense to classify and transform into array every time you pick up a piece of data. You need to understand what you’re using, what happens to each piece of code, the costs of it, how it operates. Don’t use anything without completely understanding how it works, otherwise you won’t be learning to program, you’re just kicking something to see the result.

Then just ask for all the data in, a loop and then do only two loops that prints already filtering and sorting as you ask during printing, without making any conversion.

If it’s not enough you’ll have to leave LINQ and make a single loop to separate and classify the data.

using static System.Console;
using System.Linq;
 
public class Program {
    public static void Main() {
            int numero = int.Parse(ReadLine());
            int[] arr = new int[numero];
            for (int i = 0; i < arr.Length; i++) arr[i] = int.Parse(ReadLine());
            foreach(var item in arr.Where(x => x % 2 == 0).OrderBy(x => x)) WriteLine(item);
            foreach(var item in arr.Where(x => x % 2 != 0).OrderByDescending(x => x)) WriteLine(item);
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

I did not check the validity of the data entry because it is only an exercise that will be tested automatically and the entry will be correct, but if a human were to type and enter something invalid the application would break. So keep in mind that this is not how you make real application, it was made like this because it is to pass in URI.

See more in:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.