Created
November 8, 2016 20:03
-
-
Save sleemer/3a83f6de8d64249ae4b28e8e5c66ad29 to your computer and use it in GitHub Desktop.
Implementation of variation of 'The stock span problem'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://www.hackerrank.com/challenges/poisonous-plants/submissions/code/31921305 | |
// Stack will be used to track series of plants splitted by the survived plants. | |
// Stack is a tuple of index of plant and amount of day that it will servive (0 - will live forever). | |
// eaxamle input: 3 7 1 2 4 8 2 7 9 | |
// serie splitter: | | | |
// index: 0 1 2 3 4 5 6 7 8 | |
// amount of days: 0 1 0 1 1 1 2 1 1 | |
// maximum: 2 | |
public int PoisonousPlants(string input) | |
{ | |
var plants = input | |
.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) | |
.Select(int.Parse) | |
.ToArray(); | |
var stack = new Stack<Tuple<int, int>>(); | |
stack.Push(new Tuple<int, int>(0, 0)); | |
var maxDays = 0; | |
for (int i = 1; i < plants.Length; i++) | |
{ | |
int days = 0; | |
while (stack.Count > 0 && plants[stack.Peek().Item1] >= plants[i]) | |
{ | |
days = Math.Max(days, stack.Pop().Item2); | |
} | |
days = stack.Count == 0 ? 0 : (days + 1); | |
maxDays = Math.Max(maxDays, days); | |
stack.Push(new Tuple<int, int>(i, days)); | |
} | |
return maxDays; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment