Maximum removal from array when removal time >= waiting time in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array of N elements. Our task is to find the maximum removal from the array when removal time >= waiting time.

So, here we will be removing the elements of the array. The value of the element of the array denotes the removal time(time taken to remove the element from the array).

The element has a waiting time which is the time it will have to wait till it will get removed.

The element can be removed from the only if the removal time is greater than the time it has to wait.

We have to find the maximum number of elements that can be removed from the array. The order of elements in the array can be changed as per requirement.

let's take an example to understand the problem,

Input − array = {12, 3, 11, 7, 5}

Output − 2

Explanation

First, we will reorder the array to ascending order −

The array will be {3, 5, 7,11, 12}

Now, we will remove elements one by one

Removing 3 − waiting time is 0 which is less than removal time (3). Removal is possible.

Removing 5 − waiting time is 3 which is less than removal time (5). Removal is possible.

Removing 7 − waiting time is 8 which is greater than removal time(7). Removal is not possible.

To solve this problem, we will sort and one by one check elements to be removed.

Algorithm

Step 1: Sort the array in ascending order.
Step 2: For every element in the array, Do:
Step 3: Find waiting Time (sum of removal time of all elements before the element).
Step 4: if (waiting time <= removal time )
   step 4.1: remove the element and increase the remove count.
Step 5: else: break.
Step 6: print the number of elements removed.

Example

Program to find the Maximum removal from array when removal time >= waiting time in C++

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int countRemovedElements(int arr[], int n){
   sort(arr, arr + n);
   int removeCount = 0;
   int waitTime = 0;
   for (int i = 0; i < n; i++) {
      if (arr[i] >= waitTime) {
         removeCount++;
         waitTime += arr[i];
      }
      else
         break;
   }
   return removeCount;
}
int main(){
   int arr[] = { 12, 3, 11, 7 , 5 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The maximum number of elements that can be removed from the array is "<<countRemovedElements(arr, n);
   return 0;
}

Output

The maximum number of elements that can be removed from the array is 2
raja
Published on 21-Jan-2020 15:50:35
Advertisements