Wednesday, July 4, 2018

Poisonous Plants

There are a number of plants in a garden. Each of these 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. 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.
For example, pesticide levels . Using a -indexed array, day  plants  and  die leaving . On day , plant  of the current array dies leaving . As there is no plant with a higher concentration of pesticide than the one to its left, plants stop dying after day .
Function Description Complete the function poisonousPlants in the editor below. It must return an integer representing the number of days until plants no longer die from pesticide.
poisonousPlants has the following parameter(s):
  • p: an array of integers representing pesticide levels in each plant
Input Format
The first line contains an integer , the size of the array .
The next line contains  space-separated integers .
Constraints
Output Format
Output an integer equal to the number of days after which no plants die.
Sample Input
7
6  5  8  4  7  10  9
Sample Output
2
Explanation
Initially all plants are alive.
Plants = {(6,1), (5,2), (8,3), (4,4), (7,5), (10,6), (9,7)}
Plants[k] = (i,j) => jth 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 2nd day the plants stop dying.

import java.util.Scanner;
import java.util.Stack;
public class PP {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int[] ar = new int[sc.nextInt()];
        for (int i = 0; i < ar.length; i++) {
            ar[i] = sc.nextInt();
        }
        Stack<Integer> st = new Stack<Integer>();
        int i = ar.length - 1;
        boolean day1 = false;
        int maxsize = 0, minsize = 0, days = 0;
        while (i >= 0) {
            while (i > 0 && ar[i] > ar[i - 1]) {
                i--;
                day1 = true;
            }
            // TODO Setup your maxsize and minsize            
            while (st.size() > 0 && ar[i] < st.peek())
                st.pop();
            // TODO Calc days            
            st.push(ar[i--]);
        }
        System.out.println(days + (day1 ? 1 : 0));
    }
}
ref:https://www.hackerrank.com/challenges/poisonous-plants/problem

No comments:

Post a Comment

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...