Monkey in the Garden

In a garden, trees are arranged in a circular fashion with an equal distance between two adjacent trees. The height of trees may vary. 
Two monkeys live in that garden and they were very close to each other. 
One day they quarreled due to some misunderstanding. None of them were
ready to leave the garden. But each one of them wants that if the other
wants to meet him, it should take the maximum possible time to reach him,
given that they both live in the same garden.
The conditions are that a monkey cannot directly jump from one tree to another.
There are 30 trees in the garden. If the height of a tree is H, a monkey can live at any height from 0 to H. Let's say he lives at the height of K 
then it would take him K unit of time to climb down to the ground level.
Similarly, if a monkey wants to climb up to K height it would again take K units
of time. The time to travel between two adjacent trees is 1 unit. 
A monkey can only travel in a circular fashion in the garden because there is a pond at the center of the garden.

So the question is where should two monkeys live such that the traveling time between them is maximum while choosing the shortest path between them in any direction clockwise or anti-clockwise? You have to answer only the maximum traveling time.

Example:
Input:  n = 5, h={1,2,3,4,5}
Output: 8

Approach

Java

import java.util.*;
import java.io.*;

public class MonkeyGarden {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int totalTree=sc.nextInt();

        int maxCost0;

        int costTotravelunitDistance=1;

        List<IntegerheightList = new LinkedList<Integer>(); 

        //taking the height input for n number of trees
        for(int i=1;i<=totalTree;i++) {

            int height=sc.nextInt();

            heightList.add(height);
        }

        for(int i=0;i<heightList.size()-1;i++) {
            
            int tempCost=(heightList.get(i)*
costTotravelunitDistance)+
(costTotravelunitDistance*1)+
(heightList.get(i+1)*costTotravelunitDistance);
           
 maxCost=Math.max(maxCost, tempCost);
        }
        System.out.println(maxCost);
        
    }

}


No comments:

Post a Comment