Minimize Cost with Replacement with other allowed in C++

C++Server Side ProgrammingProgramming

Suppose we have an array with N elements. We have to remove element from the array by following the given operations. The operation is like, we have to choose any two numbers of the array, and remove larger. Cost including in this operation is the same as the smaller number. We have to delete only one element at a time, based on this operation, and perform the task in minimum cost. Suppose the array has {4, 2, 5}. I take 4 and 2, remove 4 by paying cost 2, then we remove 5 again with cost 2.

The approach is too simple. As we know that the cost will be the same as the smaller one, so to reduce the cost, we will take the smallest one, and some other element, then remove the larger one, the cost will be the smaller one all the time. So the total cost will be (N – 1)*smallest number.

Example

 Live Demo

#include <iostream>
#include <algorithm>
using namespace std;
int getMinimumCost(int arr[], int n) {
   int smallest = *min_element(arr, arr+n);
   return smallest * (n - 1);
}
int main() {
   int arr[] = { 4, 2, 5 };
   int n = sizeof(arr)/sizeof(arr[0]);
   cout << "Minimum cost: " << getMinimumCost(arr, n);
}

Output

Minimum cost: 4
raja
Published on 21-Oct-2019 07:18:24
Advertisements