We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Here is a solution in Javascript and with comments:
Passes all tests
credits to ydvimalrajdy for the algorithm
functionprocessData(input){// Input parsinginput=input.split('\n');input.shift();//nvarplants=input.shift().split(' ').map(p=>parseInt(p));//SolutionvarmaxDaysAlive=0;varstack=[];// We keep in the stack the possible// killers for plants that we haven't seen yet.for(vari=0;i<plants.length;i++){vardaysAlive=0;// Number of days the plant[i] will survivewhile(stack.length>0&&plants[i]<=stack[stack.length-1].plant)daysAlive=Math.max(daysAlive,stack.pop().days);// The daysAlive for plant[i] is the max// days of all the plants greater than plant[i]// that are in the stack (possible killers) because// they all need to die before plant[i] dies.// Later we add 1 because it dies after the// other plants have died.// when plant[i] is the minimum seen until now.// It will never die.if(stack.length===0)daysAlive=0;// plant[i] will die, because it exited the while// loop and a lower plant was foundelsedaysAlive+=1;maxDaysAlive=Math.max(maxDaysAlive,daysAlive);// plant[i] is a possible killer because there // may be plants greater than this that we have // not seen yetstack.push({plant:plants[i],days:daysAlive});}console.log(maxDaysAlive);}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Poisonous Plants
You are viewing a single comment's thread. Return to all comments →
Here is a solution in Javascript and with comments: Passes all tests
credits to ydvimalrajdy for the algorithm