- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Minimize Cost with Replacement with other allowed in C++

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

#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