Distribute values from one Array to a different

0
8
Adv1

Adv2

Given N and M which is the dimensions of the array a[] and b[] respectively. You need to distribute every component from array b to array a such that the assigned worth to every component in a, must be better than or equal to the present worth in a, the duty is to return the most variety of such legitimate distributions.

Examples:

Enter: N = 3, M = 2, a [ ] = {1, 2, 3}, b [ ] = {1, 1}
Output: 1
Clarification: The values of the array a[] are 1, 2, and three.
And regardless that you’ve got 2 values in array b[], since their dimension is each 1, you would distribute just one component(1) from b to a.
You have to return 1.

Enter: N = 2 , M = 3, a [ ] = {1, 2}, b [ ] = {1, 2, 3}
Output: 2
Clarification: The values of the array a[] are 1, 2.
You’ve 3 values in array b[] and their sizes are sufficiently big to distribute to the entire components in array b[].

Strategy: To unravel the issue observe the beneath concept:

We’ll use a grasping method right here. We’ll first type each arrays in ascending order. Then traverse concurrently each arrays. If the present component in b[] is bigger or equal to the present component in a[], we distribute it and improve the indices of each arrays. If not, transfer to the subsequent index in b[], and examine once more. Proceed this, till all components are coated like these from array b[].

Steps that have been to observe the above method:

• Type the arrays a and b in ascending order.
• Initialize i and j to 0, and rely to 0.
• Whereas i is lower than N and j is lower than M, repeat steps 4 to six.
•  If b[j] is bigger than or equal to a[i], increment rely and each i and j.
• If not, increment j.
• Repeat earlier steps till all components have been thought-about from array, b, or a.
• Return rely as the reply.

Beneath is the code to implement the above method:

Java

 import java.util.Arrays;    public class GFG {     static int maxChildren(int N, int M, int greed[],                            int sz[])     {         Arrays.type(greed);         Arrays.type(sz);         int i = 0;         int j = 0;         int rely = 0;            whereas (i < N && j < M) {             if (sz[j] >= greed[i]) {                 rely++;                 i++;                 j++;             }             else {                 j++;             }         }            return rely;     }             public static void essential(String[] args)     {         int N = 3;         int M = 2;         int[] greed = { 1, 2, 3 };         int[] sz = { 1, 1 };            int outcome = maxChildren(N, M, greed, sz);                     System.out.println(outcome);     } }

Time Complexity: O(max( N*logN, M*logM ))
Auxiliary Area: O(1)

Adv3