Find high interval value

Question
Given a set of entries, each containing a time index and a int count value, i.e.
class Entry
{
time:int
count:int
}

Write a function that will give the time interval with the highest count together, i.e.

if we had entries
100, 2
100, 1
110, 10
200, 4
1000, 3
1200, 8
and we ran something like int highestInterval( 50 ); it would return 100, because in 100-150, you have counts 2, 1, and 10.

Answer

    class Program
    {
        static void Main(string[] args)
        {
            var inputs = new[] {
                new [] {100, 2 },
                new [] {100, 1 },
                new [] {110, 10 },
                new [] {200, 4 },
                new [] {1000, 3 },
                new [] {1200, 8 }
            };

            int range = 50;
            int value = HighestInterval(inputs, range);
        }

        private static int HighestInterval(int[][] inputs, int range)
        {
            int start = 0;
            int end = 0;
            int total = 0;
            int maxIndex = 0;
            int maxTotal = 0;
            int size = inputs.GetLength(0);

            do
            {
                while (inputs[end][0] - inputs[start][0]  > range){
                    total-=inputs[start][1];
                    start++;
                }

                total += inputs[end][1];

                if (maxTotal < total){
                    maxIndex = start;
                    maxTotal = total;
                }

                end++;
            }while (end < size);

            return inputs[maxIndex][0];
        }
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s