Question: We are given an array of 2n integers wherein each pair in this array of integers represents the year of birth and the year of death of a dinosaurs respectively. The range of valid years we want to consider is [-100000 to 2005]. For example, if the input was:
-80000 -79950 20 70 22 60 58 65 1950 2004
it would mean that the first dinosaur had a birth year of ?80000 and an year of death of ?79950 respectively. Similarly the second dinosaur lived from 20 to 70 and so on and so forth.
We would like to know the largest number of dinosaurs that were ever alive at one time. Write a method to compute this, given the above array of 2n integers.
Write one of the following methods: C/C++: int findmaxdinosaur (int[] years);
Java : public int findMaxdinosaur (int[] years);
wow i got also same program. ok leave it. in this program they are passing the array to us, which contains 2n integer it means what ever they enter in it they are in pair like [birth,death],[birth,death]......remember it's a single dimension array not a 2d.they gave us a example give a look on it now........
the output should be how many dinosaur are alive more in a year. that's all. it's very easy just read the question atleast 5 times u can solve it. ok Best Of Luck to it.
public int findMaxdinosaur (int[] years) {
int[] birthDino = new int[years.length]; int[] deathDino=new int[years.length]; //Now birth & death list is made in which death contains even place. for(int i=0;i<=years.length-2;i=i+2){ birthDino[i]=years[i]; deathDino[i+1]=years[i+1]; } Arrays.sort(birthDino); Arrays.sort(deathDino); List<Integer> al=new ArrayList<Integer>();//List is need because i need to remove null values from here for(int aa: birthDino){ al.add(aa); } al.removeAll(Collections.singleton(0));// Removing all positions which contain null values // System.out.println(al); List<Integer> all=new ArrayList<Integer>(); for(int aa: deathDino){ all.add(aa); //adding in to the List } all.removeAll(Collections.singleton(0)); int Alive=0,maxDinos=0,LastBornMax=0; int b = 0,d=0; while( b!=birthDino.length && d!=deathDino.length) { if (birthDino[b] < deathDino[d]) { Alive = Alive + 1; b = b + 1; } else { Alive = Alive - 1; d = d + 1 ; } if(maxDinos < Alive){ //checking the values maxDinos = Alive; LastBornMax=birthDino[b-1]; } }//while end //S N Prasad Rao return maxDinos; }//end of method
Ads