Car engine hackerrank solution in java




Car Engine Hackerrank Solution in Java

Car Engine Hackerrank Solution in Java

Problem Statement

You are given a list of car engines, each with a different speed and fuel consumption. You need to find the engine that has the best fuel efficiency, which is defined as the ratio of speed to fuel consumption.

Input Format

The input consists of two lines. The first line contains the number of engines, n. The second line contains n pairs of integers, where each pair represents the speed and fuel consumption of an engine.

Output Format

Output the index of the engine with the best fuel efficiency. If there are multiple engines with the same best fuel efficiency, output the index of the engine with the highest speed.

Sample Input

4
10 3
15 5
20 7
25 10
  

Sample Output

3
  

Solution

import java.util.Scanner;

public class CarEngine {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int n = scanner.nextInt();

        // Create an array to store the engines
        Engine[] engines = new Engine[n];

        // Read the input and create the engines
        for (int i = 0; i < n; i++) {
            int speed = scanner.nextInt();
            int fuelConsumption = scanner.nextInt();

            engines[i] = new Engine(speed, fuelConsumption);
        }

        // Find the engine with the best fuel efficiency
        int bestEngineIndex = -1;
        double bestFuelEfficiency = Double.MIN_VALUE;

        for (int i = 0; i < n; i++) {
            double fuelEfficiency = engines[i].getFuelEfficiency();

            if (fuelEfficiency > bestFuelEfficiency) {
                bestFuelEfficiency = fuelEfficiency;
                bestEngineIndex = i;
            } else if (fuelEfficiency == bestFuelEfficiency) {
                if (engines[i].getSpeed() > engines[bestEngineIndex].getSpeed()) {
                    bestEngineIndex = i;
                }
            }
        }

        // Output the index of the engine with the best fuel efficiency
        System.out.println(bestEngineIndex + 1);
    }

    private static class Engine {

        private final int speed;
        private final int fuelConsumption;

        public Engine(int speed, int fuelConsumption) {
            this.speed = speed;
            this.fuelConsumption = fuelConsumption;
        }

        public int getSpeed() {
            return speed;
        }

        public int getFuelConsumption() {
            return fuelConsumption;
        }

        public double getFuelEfficiency() {
            return (double) speed / fuelConsumption;
        }
    }
}
  


Like this post? Please share to your friends:
Leave a Reply