Amazon OA Question With Solution

 

amazon oa



Approach:

Step 1: Create a HashMap

  • Initialize a HashMap to store the package weights as keys and their respective frequencies as values.

Step 2: Iterate Through the Keyset

  • Loop through all the keys in the keyset of the HashMap.

Step 3: Check the Frequency of Each Key

  • For each key, retrieve its frequency from the HashMap using map.get(key).

Step 4: Determine Divisibility

  • Check if the frequency is divisible by 2.
    • If it is, calculate how many trips are needed by dividing the frequency by 2 and add the result to the trips variable.
  • Check if the frequency is divisible by 3.
    • If it is, calculate how many trips are needed by dividing the frequency by 3 and add the result to the trips variable.

Step 5: Handle Both Divisibilities

  • If the frequency is divisible by both 2 and 3, compare the trips calculated for both conditions.
    • Use the minimum number of trips (Math.min(map.get(key)/2, map.get(key)/3)) and add it to the trips variable.

Step 6: Update the Total Trips

  • Add the calculated trips for each key to the trips variable to get the cumulative number of trips required.

Step 7: Finalize the Result

  • After completing the iteration for all keys, the trips variable will hold the total number of trips required based on the given conditions.


CODE:

package Hashing;

import java.util.HashMap;

public class AmazonOA2 {

    public static void main(String[] args) {

        int [] pw={2,4,6,6,4,2,4,6,6,6,6};

        int trips=0;

        boolean flag=false;

        HashMap<Integer,Integer> map=new HashMap<>();

        for(int weight:pw){

            map.put(weight,map.getOrDefault(weight, 0)+1);

        }

        for(int key:map.keySet()){

            if(map.get(key)%2==0 && map.get(key)%3!=0){

                trips+=(map.get(key)/2);

            }

            else if(map.get(key)%3==0 && map.get(key)%2!=0){

                trips+=(map.get(key)/3);

            }

            else if(map.get(key)%3==0 && map.get(key)%2==0){

                trips+=Math.min((map.get(key)/2),(map.get(key)/3));

            }

            else{

                flag=true; //finds a weight which is not allowed to deliver acc. to rules.

                break;

            }

        }

        if(flag){

            System.out.println(-1);

        }

        else{

            System.out.println(trips);

        }

    }

}


If you have any doubt feel free to comment down below👇

Comments