×

Monsoon Umbrella Problem in Java

The Monsoon Umbrella problem is a classic Java programming problem used to test the skills of a programmer. The problem involves writing a program to determine the number of umbrellas a person needs to buy to stay dry during a monsoon season. It is a problem that requires a programmer to compute the minimum number of umbrellas needed to cover a given set of people during a monsoon season. The program must then output the total number of umbrellas the person needs to buy to stay dry throughout the season.

Case 1:

In this problem, several people will be given. Based on the size of the umbrellas, we need to find the minimum number required to cover the given number of people. The size of the umbrella indicates the maximum number of people an umbrella can cover. If the size of an umbrella is 2, then it indicates it can cover a maximum of 2 people.

Example

Input: Number of people = 10

Size of umbrella =2

Output: Minimum number of Umbrellas required: 5

File Name: MonsoonUmbrella.java

// Importing required packages
import java. util.*;
// public class declaration
public class MonsoonUmbrella
{
    // Main section of the program where the execution of the program begins
	public static void main(String[] args) {
	    // creating object for scanner class
	    Scanner sc=new Scanner(System.in);
	    // Enter the number of people
	    System. out.println("Enter number of people");
	    int n=sc.nextInt();
	    // Enter umbrella size
	    System. out.println("Enter the  umbrella size");
	    int us=sc.nextInt();
	    // Printing the Minimum number of umbrellas required
	    System. out.println("The Minimum number of umbrellas required is "+(n/us));
		
	}
}

Output:

Enter the number of people
10
Enter umbrella size
2
The minimum number of umbrellas required is 5

Case 2

Several umbrellas, ‘N’, of different sizes will be given. We need to find the minimum number of umbrellas required to cover the ‘K’ number of people. If there is no combination of umbrellas to cover, return -1.

Input Format

The First Line’s first value is the number of umbrellas array size(N), and the second integer is the number of people (K)

The second line contains all the different sizes of umbrellas.

Input

3 30

[5 10 25]

Output: 2

Explanation

One umbrella can hold 25 people, and the other can hold 5.

Using Dynamic Programming

The goal is to solve one subproblem first, then use the solutions from that subproblem to solve other subproblems using dynamic programming.

Algorithm

  • Create a 2D array of size (N + 1) * (M + 1) called DP[][], where DP[i][j] is the bare minimum number of umbrellas needed to cover j individuals with the first I umbrellas.
  • Iterate from I = 0 to N, j = 0 to N, etc.
  • If j == 0, no umbrellas are needed because no persons need to seek cover.
  • Placing DP[i][j] at 0.
  • Else, We no longer have enough umbrellas to cover M individuals if I == 0.
  • DP[i][j] = INF is set.
  • Else, Set DP[i][j] to DP[i - 1][j], i.e., stop considering the i-th umbrella.
  • Update DP[i][j] to min(DP[i][j], 1 + DP[i - 1][j - UMBRELLA[i - 1] i.e. taking into account the i-th umbrella if j >= UMBRELLA[i - 1].
  • Because we must determine the bare minimum of umbrellas necessary to cover M persons with the first N umbrellas, we must declare an integer variable ANS and set it to DP[N][M].
  • Return ANS if ANS >= INF; otherwise, return -1.

File Name: MinimumUmbrellaRequired.java

public class MinimumUmbrellaRequired {
    public static void main(String s[])
    {
        int umbrella[]={5,10,25};
        int m=30;
        int ans=minNumberUmbrellas(umbrella,m);
        System.out.println(ans);
    }
    public static int minNumberUmbrellas(int[] umbrella, int m)  {
        int n = umbrella.length, inf = (int)1e9 + 5;


        int[][] dp = new int[n + 1][m + 1];


        for (int i = 0; i <= umbrella.length; i++) {
            for (int j = 0; j <= m; j++) {


                if (j == 0) {
                    dp[i][j] = 0;
                }


                else if (i == 0) {
                    dp[i][j] = inf;
                } else {
                    dp[i][j] = dp[i - 1][j];


                    if (j >= umbrella[i - 1]) {
                        dp[i][j] = Math.min(dp[i][j], 1 + dp[i - 1][j - umbrella[i - 1]]);
                    }


                }


            }
        }


        int ans = dp[n][m];


        if (ans >= inf) {
            return -1;
        }


        return ans;
    }
}

Output

2

Complexity Analysis

Time Complexity

Time Complexity is O(N * M), where N is the variety of umbrellas available and M is the number of persons who will need to use umbrellas to protect themselves.

Space Complexity

As we are utilizing a 2D auxiliary array of order N * M. The total complexity of the space is O(N * M).


Related Topics

Java Math.multiplyExact() method

In java, we are provided with multiplyExact method in the Math module. This Math module belongs to the java.lang package. In general, this method returns the product of the provided...

2 minutes read.

Java Date add Days

In order to operate with the time and the Date in Java, we used the abstract Calendar class. It has several helpful interfaces that enable us to convert dates between...

4 minutes read.

Java Byte Code

Java byte code is really a powerful mechanism which makes Java a portable and platform-independent programming language. There are two software components which go along and make this byte code...

3 minutes read.

How to Calculate the Time Difference between Two Dates in Java?

The date is used extensively in Java to calculate date discrepancies. The date of joining an organization, admittance, appointment, etc., can be included when creating the application. The differences between...

4 minutes read.

Java Boolean booleanValue() method

The booleanValue() method of Java Boolean class returns a Boolean value for the specified Boolean argument. Syntax public Boolean booleanValue() Parameters NA Return Value This method returns the primitive value of specified Boolean object. Example 1 public class...

2 minutes read.

How to Convert int to char in Java

To convert a higher data type to lower data type, we need to do typecasting. Casting is also required when we want to convert ASCII value into character. It is...

3 minutes read.

Java Math sqrt() Method

The sqrt() method of Java Math class returns the accurately rounded positive square root of the specified double value. Syntax: public static double sqrt(double a) Parameters: The parameter ‘a’ represents the number whose square...

2 minutes read.

Majority Element in Java

It's an extremely intriguing question that is commonly asked in job interviews at prestigious IT firms like The Google, Amazon, TCS, and The Accenture, etc. By figuring out the solution, one may...

10 minutes read.

Adapter class in Java

By using the adapter classes, we can implement Listener interfaces. With the help of adapter classes, we can save code as it provides all implementation methods of listener interfaces Advantages of...

3 minutes read.

Java RandomAccessfile

Writing and reading to random access files are done using this class. An array of many bytes is how a random access file operates. By changing the implied file pointer...

3 minutes read.

Vector in Java

Java Vector Class The Vector class is a legacy class that implements a growable array of objects. The components that it contains can be accessed using an integer index. The size of...

26 minutes read.

Selection Sort in Java

Selection Sort in Java Selection sort is also a simple sorting algorithm that works by repeatedly finding the minimum element from the unsorted portion of the input array, and placing it...

5 minutes read.

How to Call a Method in Java

In Java, a method is a collection of statements that perform a specific task or action.It can accept data with the help ofitsarguments. It  is also called a function. In order...

9 minutes read.

Prime Number Program in Java

Prime Number Program in Java using for loop A natural number which is greater than 1 and has only two factors the number itself and 1 is called prime number. In...

2 minutes read.

Java Custom Exception

Java Custom Exception Java language facilitates us to create our own exceptions. The class intended to throw the Custom Exception has to be derived from the Java Exceptionor RuntimeExceptionclass. The Java...

4 minutes read.

Properties Class in Java

Properties class is associated with Java since JDK 1.0, i.e. it is a legacy class. It is the subclass of Hashtable. It is used to maintain the lists of values in which...

5 minutes read.

Web Service Response Time Calculation in Java

Administration response time or reaction time is the typical measure of time it takes for a solicitation to be handled by a PC framework, like your organization switch. In the...

4 minutes read.

How to Convert double to int in Java

The double is a larger data type than int. When we assign a larger type value to a variable of smaller type, then we need to perform the explicit conversion....

2 minutes read.

Java Boolean compare() method

The compare() method of Java Boolean class compares the specified Boolean values and returns a positive 1 or negative 1 or zero integer value based on the result. Syntax public static int...

2 minutes read.

How to Convert Object to String in Java

How to Convert Object to String in Java You can convert any Object to String in Java whether it is a user-defined class, StringBuilder or StringBuffer, etc. There are two methods...

2 minutes read.