I have the solution for the problem, but it is taking me 7 seconds to run on a large dataset. I am trying figure out a better way of doing this. It has to run in under 3 seconds.
Problem Statement:
There are N plants in a garden. Each of these plants has been added with some amount of pesticide. After each day, if any plant has more pesticide than the plant at its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each plant. Print the number of days after which no plant dies, i.e. the time after which there are no plants with more pesticide content than the plant to their left.
Explanation:
Initially all plants are alive.
- Plants = \$\{(6,1), (5,2), (8,3), (4,4), (7,5), (10,6), (9,7)\}\$
- Plant = \$(i,j)\$ \$\Rightarrow\$ \$j\$th plant has pesticide amount \$i\$.
- After the 1st day, 4 plants remain as plants 3, 5, and 6 die.
- Plants = \$\{(6,1), (5,2), (4,4), (9,7)\}\$
- After the 2nd day, 3 plants survive as plant 7 dies.
- Plants = \$\{(6,1), (5,2), (4,4)\}\$
- After the 3rd day, 3 plants survive and no more plants die.
- Plants = \$\{(6,1), (5,2), (4,4)\}\$
I added the test case to this Pastebin.
static void Main(string[] args)
{
Stopwatch timer = new Stopwatch();
timer.Start();
string data = "";// Console.ReadLine(); //"6 5 8 4 7 10 9";
foreach (var line in File.ReadLines(@"FilePath"))
{
data = line;
}
bool happyState = false;
bool plantDied = false;
int numberOfDays = 0;
LinkedList<int> lstPlants = new LinkedList<int>(data.Split(new char[] { ' ', '\t' }).Select(s => int.Parse(s)).ToList());
LinkedListNode<int> lastNode = lstPlants.Last;
LinkedListNode<int> currentNode = lstPlants.First;
int cValue = currentNode.Value;
while (!happyState)
{
numberOfDays++;
plantDied = false;
happyState = false;
lastNode = lstPlants.Last;
currentNode = lstPlants.First;
cValue = currentNode.Value; //bug fix
while (currentNode != lstPlants.Last)
{
if (currentNode.Next.Value > cValue)
{
plantDied = true;
cValue = currentNode.Next.Value;
lstPlants.Remove(currentNode.Next);
//currentNode = currentNode.Next;
}
else
{
currentNode = currentNode.Next;
cValue = currentNode.Value;
}
}
if (!plantDied)
{
numberOfDays--;
happyState = true;
}
}
timer.Stop();
Console.WriteLine("Time taken to calculate is {0} seconds and the answer is {1}.", timer.Elapsed.TotalSeconds, numberOfDays);
Console.ReadLine();
}