×

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 For Keyword

For as a keyword in java: When we need to run a set of statements repeatedly in Java, we use loops. The Java for loop offers a clear way to express...

4 minutes read.

Java.net.ConnectionException

java.net.ConnectException: Connection rejected: the interface is the most continuous sort of happening, organizing special cases in Java at whatever point the product is in client-server engineering and attempting to make...

3 minutes read.

Java Serialization

JAVA SERIALIZATION Serialization is a process by which objects can be represented as a sequence of bytes. These bytes have information about object's data, object's type and datatypes of members in...

3 minutes read.

Sierpinski Number in Java

The Sierpinski triangle—is it a fractal? The Sierpinski Triangle fractals. A self-similar fractal is the Sierpinski triangle. It is made of an equilateral triangle with its residual area successively reduced by...

3 minutes read.

Compare time in java

Introduction: This article discusses how to compare time in java. Maximum of the time we need to examine the date and datetime items. Date comparisons are vital if you want to...

3 minutes read.

Reverse a String using Collections in Java

Generally, a String is a grouping of characters. Yet, in Java, a String is an item that addresses a succession of characters. The Java.lang.String class is utilized to make a...

5 minutes read.

Java Control Statements

Control Statements: Control statements in Java can also be referred to as decision-making while dealing with different problems. Control statements are helpful to sort out the flow of the program or...

7 minutes read.

Difference Between in Java and C++

FeatureC++JavaDefinitionC++ is a general programming language created by Bjarne Stroustrup as an extension of c language    Java is class-based, object-based, and designed to have as few implementation dependencies as...

4 minutes read.

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.

How to Update Java

As we all know that java can be installed in all operating systems like windows, Linux, macOS. We are available with the java 17 and java 18 versions in the...

3 minutes read.

Java Math IEEEremainder() Method

The IEEEremainder() method of Math class calculates the remainder as prescribed by the IEEE754 standard. This method simply returns the remainder when f1 (dividend) is divided by f2 (divisor). Syntax: public static...

2 minutes read.

Constructor Overloading in Java

In Java, constructors can be overloaded just like methods. The idea of having multiple constructors with various parameter sets so that each function Object()  can carry out a particular task...

3 minutes read.

Java Rename File

Renaming a file is the process of changing its name. Using the renameTo() function of the Java File class, renaming operations are possible. A file can be renamed using Java's renameTo()...

3 minutes read.

GCD Program in Java

GCD Program in Java The GCD program in Java outputs the GCD of the given numbers. In mathematics, Greatest Common Divisor (GCD), Greatest Common Factor or Highest Common Factor (HCF) of...

14 minutes read.

Ternary Operator in Java

In some cases, the if...else expression in Java can be replaced by a ternary operator. Visit the Java if...else statement first before learning about the ternary operator. Ternary operator in Java A...

3 minutes read.

Java Transient

Java Transient In Java, Serialization is used to convert an object into a stream of the byte. The byte stream consists of the data of the instance as well as the...

3 minutes read.

Java Math toIntExact() Method

The toIntExact() method of Java Math class returns the int value of the given long argument, throwing an exception if the value overflows an int. Syntax: public static int toIntExact (long value) Parameters: The...

2 minutes read.

Split the Number String into Primes in Java

Given is a string that only contains digits and serves to represent a number. Our goal is to split the string of numbers in a way that ensures each segment...

2 minutes read.

Longest Odd Even Subsequence in Java

In order to solve the Java problem known as the longest odd-even subsequence, one must identify a sequences in a non-negative array having size s that alternately includes odd and...

6 minutes read.

How to Convert Decimal to Octal in Java

How to Convert Decimal to Octal in Java There are two methods to convert Decimal to Octal: Using toOcatlString() method Using user-defined logic Using Integer.toOctalString() method The toOctalString() is astaticmethod of the Integer...

2 minutes read.