Poisonous Plants | Solution | Explanation | C++

Raunit Verma - in Coding
Views: 0

There are a number of plants in a garden. Each of the plants has been treated with some amount of pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each of the plants. Determine the number of days after which no plant dies, i.e. the time after which there is no plant with more pesticide content than the plant to its left.

Solution

The solution uses a stack to track plants and determine the maximum number of days until no more plants die. Here's how it works:

  • Setup: A stack stores pairs of (index, span), where span is the number of days a plant will take to die. ans tracks the maximum days.
  • Iteration: For each plant v[i]:
    • Start with cnt = 1 (minimum days require for current plant to die).
    • While the stack isn’t empty and the top plant’s pesticide level is ≥ v[i], pop it and update cnt to reflect the chain of deaths (adding 1 to the popped plant’s span). The plant on the left will die first.
    • If the stack empties, set cnt = 0 (no left neighbor).
    • Update ans with the maximum cnt and push the current plant onto the stack.
  • Sample Walkthrough: For [6, 5, 8, 4, 7, 10, 9]:
    • Day 1: Plants 8, 7, and 10 die, leaving [6, 5, 4, 9].
    • Day 2: Plant 9 dies, leaving [6, 5, 4].
    • The stack computes this as a chain, yielding ans = 2.
  • Complexity: O(n) time and space, as each plant is pushed/popped once.
int solve(vector<int> v)
{

  stack<pair<int, int>> st;
  int ans = 0;
  vi span(v.size(), -1);

  for (int i = 0; i < v.size(); i++)
  {
    int cnt = 1;
    while (!st.empty() && v[st.top().first] >= v[i])
    {
      cnt = max(cnt, st.top().second + 1);
      st.pop();
    }
    if (st.empty())
      cnt = 0;
    ans = max(ans, cnt);
    st.push({i, cnt});
  }

  return ans;
}
TagsPoisonous PlantsHackerrankPoisonous Plants Hackerrank SolutionC++DSA
Raunit Verma-picture
Raunit Verma

Technical Writer at CodingKaro

Share this on
CodingKaro Poster
CodingKaro
4.7

3K+ Downloads

One of its unique features is an automated coding contest reminder, which sets alarms for upcoming coding contests on popular platforms like CodeChef, CodeForces, and LeetCode, without the need for user input. This feature ensures that users never miss a coding contest and can stay updated with the latest coding challenges.

Download CodingKaro
Other Blogs in Coding