Poisonous Plants


Problem Statement :


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.

Example

p = [ 3, 6, 2, 7, 5  ] // pesticide levels

Use a 1-indexed array. On day  1, plants  2 and 4 die leaving p' = [ 3, 2, 5 ] . On day ,2, plant 3  in p'  dies leaving p^n  = [ 3, 2 ]. There is no plant with a higher concentration of pesticide than the one to its left, so plants stop dying after day 2.


Function Description
Complete the function poisonousPlants in the editor below.

poisonousPlants has the following parameter(s):

int p[n]: the pesticide levels in each plant
Returns
- int: the number of days until plants no longer die from pesticide

Input Format

The first line contains an integer n, the size of the array p.
The next line contains n  space-separated integers p[ i ] .



Solution :



title-img


                            Solution in C :

In   C :







#include<stdio.h>
int main(){
    long int n,i,j,min=0,locmin;
    scanf("%ld",&n);
    long long int *p=(long long int *)malloc(sizeof(long long int)*n);
    for(i=0;i<n;i++)
    scanf("%lld",&p[i]);
    
    i=n-2;
    j=n-1;
    
    while(i>=0){
               if(j<n && p[j]>p[i]){
                      locmin=0;
                              while(j<n && (p[j]>p[i] || p[j]<0)){
  
                              
                              //if(p[j-1]<0)
                              if(p[j]>0)
                              p[j]=locmin-1;
                              
                              if(locmin>p[j])
                              locmin = p[j];
                              //else
                              //p[j] = -1;
                              j++;               
                              }  
               }
               j=i;
               i--;
    }
    for(i=0;i<n;i++){
                     if(p[i]<min)
                     min=p[i];
    }
    printf("%ld ",-min);
    free(p);
    return 0;
}
                        


                        Solution in C++ :

In   C ++ :






#include<iostream>
#include<cstdio>
#include<algorithm>
#include<set>
#include<map>
#include<queue>
#include<cassert>
#define PB push_back
#define MP make_pair
#define sz(v) (in((v).size()))
#define forn(i,n) for(in i=0;i<(n);++i)
#define forv(i,v) forn(i,sz(v))
#define fors(i,s) for(auto i=(s).begin();i!=(s).end();++i)
#define all(v) (v).begin(),(v).end()
using namespace std;
typedef long long in;
typedef vector<in> VI;
typedef vector<VI> VVI;
in dct=0;
map<in,in> mar;
set<in> td;
void proc(in id){
  auto it=mar.find(id);
  auto it2=it;
  ++it2;
  mar.erase(it);
  if(it2!=mar.end() && it2!=mar.begin()){
    it=it2;
    --it;
    if(it2->second>it->second)
      td.insert(it2->first);
    else{
      if(td.count(it2->first))
	td.erase(it2->first);
    }
  }
}
VI otd;
int main(){
  ios::sync_with_stdio(0);
  cin.tie(0);
  in n;
  cin>>n;
  in ta;
  forn(i,n){
    cin>>ta;
    mar[i]=ta;
    if(i>0 && mar[i]>mar[i-1])
      td.insert(i);
  }
  while(!td.empty()){
    dct++;
    otd.clear();
    fors(i,td)
      otd.PB(*i);
    td.clear();
    reverse(all(otd));
    forv(i,otd){
      proc(otd[i]);
    }
  }
  cout<<dct<<endl;
  return 0;
}
                    


                        Solution in Java :

In   Java :





import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
	
	Scanner sc = new Scanner(System.in);
	int n = sc.nextInt();
	
	int[] p = new int[n+1];
	int[] surv = new int[n+1];
	int[] index = new int[n+1];
	p[0] = Integer.MAX_VALUE;
	
	for (int i = 1; i <= n; i++)
	{
	    p[i] = sc.nextInt();
	    index[i] = i;
	}
	
	int min = p[1];
	surv[1] = -1;
	int longest = -1;
	for (int i = 2; i <= n; i++)
	{
	    
	    if (p[i] > min)
	    {
		
		int j = i -1;
		int max = 0;
		while (j >= 1 && surv[j] != -1)
		{
		    if (p[j] < p[i])
			    break;
		    max = Math.max(surv[j] + 1, max);
		    j = index[j];
		}
		surv[i] = max;
		index[i] = j;
		longest = Math.max(longest, max);
		
	    }
	    else
	    {
		surv[i] = -1;
		min = p[i];
	    }
	    
	    
	}
	
	
	
	
	System.out.println(longest+1);
	
    }
}
                    


                        Solution in Python : 
                            
In  Python3 :





class Plant:
    def __init__(self, pest):
        self.p =pest
        self.d = 0 #days passed before it reaches this point
        
input()
plants = [Plant(int(i)) for i in input().split()]
stack = [plants[-1]]
days = 0
for i in range(len(plants)-2,-1,-1):
    if len(stack)==0 or plants[i].p >=stack[-1].p:
        stack.append(plants[i])
    else:
        local = 0
        while len(stack)>0 and plants[i].p < stack[-1].p:
            local = max(local+1, stack[-1].d)
            stack.pop()
        plants[i].d = local
        days = max(local, days)
        stack.append(plants[i])
print(days)
                    


View More Similar Problems

Jesse and Cookies

Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value K. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with: sweetness Least sweet cookie 2nd least sweet cookie). He repeats this procedure until all the cookies in his collection have a sweetness > = K. You are given Jesse's cookies. Print t

View Solution →

Find the Running Median

The median of a set of integers is the midpoint value of the data set for which an equal number of integers are less than and greater than the value. To find the median, you must first sort your set of integers in non-decreasing order, then: If your set contains an odd number of elements, the median is the middle element of the sorted sample. In the sorted set { 1, 2, 3 } , 2 is the median.

View Solution →

Minimum Average Waiting Time

Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. Different kinds of pizzas take different amounts of time to cook. Also, once h

View Solution →

Merging Communities

People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w

View Solution →

Components in a graph

There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu

View Solution →

Kundu and Tree

Kundu is true tree lover. Tree is a connected graph having N vertices and N-1 edges. Today when he got a tree, he colored each edge with one of either red(r) or black(b) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex a to b, vertex b to c and vertex c to a . Note that

View Solution →