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

C++Server Side ProgrammingProgramming

Problem statement

Given an array of N elements. The task is to remove elements from the array from left to right. However, some time is required to remove an element from the array(let us call it removal time). The time to remove an element is equal to the value of the of that element in seconds.

An element can only be removed when the time required to remove it (removal time) is greater than or equal to the time it waits in the array.

Example

Example
If input array is arr[] = {7, 6, 12, 4} then output will be
3
Let us re-arrange elements in sorted order:
{4, 6, 7, 12}
  • First element takes 4 seconds to get removed hence it can be removed
  • The second element waits 4 seconds in an array and takes 6 seconds to get removed. This is more than its waiting time. Hence it can be removed.
  • The third element waits 10 seconds in an array and takes 7 seconds to get removed. This is less than its waiting time. Hence it cannot be removed.
  • The third element waits 10 seconds in an array and takes 12 seconds to get removed. This is more than its waiting time. Hence it can be removed.

Algorithm

  • Sort elements in ascending order
  • Start iterating from left side and maintain a cumulative sum of the removal time (which will serve as the waiting time for next element) Check for each element if it is present in the set
  • Check at each element, if it’s removal time is greater than or equal to the cumulative time (its waiting time). If it is less, than it cannot be removed. If it is equal or greater, than it can be removed and add its removal time in cumulative sums
  • Repeat this process for entire array

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getMaxRemoval(int *arr, int n) {
   int count = 0;
   int cummulativeSum = 0;
   sort(arr, arr + n);
   for (int i = 0; i < n; ++i) {
      if (arr[i] >= cummulativeSum) {
         ++count;
         cummulativeSum += arr[i];
      }
   }
   return count;
}
int main() {
   int arr[] = {7, 6, 12, 4};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Result = " << getMaxRemoval(arr, n) << endl;
   return 0;
}

Output

When you compile and execute above program. It generates following output −

Result = 3
raja
Published on 21-Jan-2020 11:20:35
Advertisements