Distribute values from one Array to any other

Given N and M which is the scale of the array a[] and b[] respectively. You need to distribute each and every component from array b to array a such that the assigned price to each and every component in a, must be more than or equivalent to the present price in a, the duty is to go back the most collection of such legitimate distributions.


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

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

Manner: To unravel the issue observe the under concept:

We will be able to use a grasping manner right here. We will be able to first kind each arrays in ascending order. Then traverse concurrently each arrays. If the present component in b[] is bigger or equivalent to the present component in a[], we distribute it and build up the indices of each arrays. If no longer, transfer to the following index in b[], and test once more. Proceed this, till all components are coated like those from array b[].

Steps that had been to observe the above manner:

  • Kind the arrays a and b in ascending order.
  • Initialize i and j to 0, and rely to 0.
  • Whilst i is lower than N and j is lower than M, repeat steps 4 to six.
    •  If b[j] is larger than or equivalent to a[i], increment rely and each i and j.
    • If no longer, increment j.
  • Repeat earlier steps till all components had been regarded as from array, b, or a.
  • Go back rely as the solution.

Under is the code to put into effect the above manner:


import java.util.Arrays;


public magnificence GFG {

    static int maxChildren(int N, int M, int greed[],

                           int sz[])




        int i = 0;

        int j = 0;

        int rely = 0;


        whilst (i < N && j < M) {

            if (sz[j] >= greed[i]) {





            else {





        go back rely;




    public static void major(String[] args)


        int N = 3;

        int M = 2;

        int[] greed = { 1, 2, 3 };

        int[] sz = { 1, 1 };


        int outcome = maxChildren(N, M, greed, sz);






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

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

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: