View Dialogue

Enhance Article

Save Article

Like Article

Given an array arr[] of measurement N, the duty is to seek out the minimal variety of operations required to scale back all three parts of the array to zero. Following operations are allowed:

  • Cut back 2 completely different array parts by one.
  • Cut back a single array aspect by one.

Instance:

Enter: arr[] = {1, 2, 3}, N = 3
Output: 3
Clarification : Operation 1: cut back 3 and a couple of to get {1, 1, 2}
Operation 2: reduuce 1 and a couple of to get {1, 0, 1}
Operation 3: cut back each 1s to get {0, 0, 0}

Enter: arr[] = {5, 1, 2, 9, 8}, N = 5
Output: 13

 

Method:

This drawback may be solved utilizing grasping strategy. The thought is to scale back the two largest parts at a time or (if not doable) 1 at a time.  As we want the biggest parts in every step, we will use a max heap.

The next steps may be taken to unravel this strategy:

  • Provoke a depend variable as 0.
  • Insert all the weather in a max heap.
    • Cut back the 2 largest parts.
    • Insert the lowered values once more into the heap.
  • Repeat above talked about steps till all array parts change into zero and enhance the depend at every iteration.
  • Cease when all array parts are zero.

Under is the implementation of the above strategy:

Java

import java.util.*;

  

class GFG {

  

    public static int reduceArray(int arr[], int N)

    {

  

        int depend = 0;

        PriorityQueue<Integer> pq = new PriorityQueue<>();

  

        for (int i = 0; i < N; i++) {

            pq.add(arr[i] * -1);

        }

        whereas (pq.measurement() > 1) {

            int temp1 = pq.ballot();

            int temp2 = pq.ballot();

            depend++;

            temp1++;

            temp2++;

            if (temp1 != 0)

                pq.add(temp1);

            if (temp2 != 0)

                pq.add(temp2);

        }

        if (pq.measurement() > 0)

            depend -= pq.ballot();

        return depend;

    }

  

    

    public static void essential(String[] args)

    {

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

        int N = 3;

        int depend = reduceArray(arr, N);

        System.out.println(depend);

    }

}

Time Complexity: O(N * logN)
Auxiliary Area: O(N)

By admin

Leave a Reply

Your email address will not be published.