GeeksforGeeks App
Open App
Browser
Continue

# Cost required to empty a given array by repeated removal of maximum obtained by given operations

Given an array arr[] consisting of N integers, the task is to find the cost to remove all array elements after performing the following operations in the specified order any number of times:

Examples:

Input: arr[] = {1, 6, 7, 4, 2, 5, 3}
Output: 16
Explanation:
Step 1: Current maximum element = 7. Removing 7 and reducing each element by 1 modifies the array to {0, 5, 3, 1, 4, 2}. Cost = 7.
Step 2: Current maximum element = 5. Removing 5 and reducing each element by 1 modifies the array to {2, 0, 3, 1}. Cost = 7 + 5 = 12.
Step 3: Current maximum = 3. Removing 3 and reducing each element by 1 modifies the array to {1, 1}. Cost = 12 + 3 = 15
Step 4: Final cost obtained = 15 + 1 = 16

Input: arr[] = {6, 4, 6, 1}
Output: 13

Naive Approach: The simplest approach to solve the problem is as follows:

• Find the maximum from the given array
• Add it to the cost after removing it from the array.
• Once the maximum element is removed, reduce all remaining array elements by 1. Remove all elements reducing to 0.
• Repeat the above steps until all array elements are removed.
• Finally, print the value of cost.

## C++

 `// C++ program to find the cost to remove all array elements``// after performing the specified operations.` `#include ``using` `namespace` `std;` `// Function to find the cost to remove all array elements``int` `findCost(vector<``int``>& arr, ``int` `n)``{``    ``// using long long to avoid overflow``    ``long` `long` `cost = 0;` `    ``// loop until array arr is not empty``    ``while` `(!arr.empty()) {``        ``// find the maximum element``        ``int` `max_elem = *max_element(arr.begin(), arr.end());` `        ``// add it to the cost``        ``cost += max_elem;``        ``// remove it from the array``        ``arr.erase(find(arr.begin(), arr.end(), max_elem));``        ``// reduce all remaining array elements by 1``        ``for` `(``int` `i = 0; i < arr.size(); i++) {``            ``arr[i]--;``        ``}``        ``// remove all elements reducing to 0``        ``arr.erase(``remove``(arr.begin(), arr.end(), 0),``                  ``arr.end());``    ``}` `    ``// Return the total cost``    ``return` `cost;``}` `// Driver code``int` `main()``{``    ``// Input array``    ``vector<``int``> arr = { 1, 6, 7, 4, 2, 5, 3 };``    ``int` `n = arr.size();` `    ``// Function Call``    ``int` `cost = findCost(arr, n);``    ``cout << cost << endl;` `    ``return` `0;``}`

## Java

 `// Java program to find the cost to remove all array``// elements after performing the specified operations.` `import` `java.util.*;` `public` `class` `GFG {``    ``// Function to find the cost to remove all array``    ``// elements``    ``static` `int` `findCost(ArrayList arr, ``int` `n)``    ``{``        ``// using long to avoid overflow``        ``long` `cost = ``0``;``        ``// loop until array arr is not empty``        ``while` `(!arr.isEmpty()) {``            ``// find the maximum element``            ``int` `max_elem = Collections.max(arr);` `            ``// add it to the cost``            ``cost += max_elem;``            ``// remove it from the array``            ``arr.remove(arr.indexOf(max_elem));``            ``// reduce all remaining array elements by 1``            ``for` `(``int` `i = ``0``; i < arr.size(); i++) {``                ``arr.set(i, arr.get(i) - ``1``);``            ``}``            ``// remove all elements reducing to 0``            ``arr.removeIf(e -> e == ``0``);``        ``}` `        ``// Return the total cost``        ``return` `(``int``)cost;``    ``}` `    ``// Driver code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``// Input array``        ``ArrayList arr = ``new` `ArrayList<>(``            ``Arrays.asList(``1``, ``6``, ``7``, ``4``, ``2``, ``5``, ``3``));``        ``int` `n = arr.size();` `        ``// Function Call``        ``int` `cost = findCost(arr, n);``        ``System.out.println(cost);``    ``}``}`

## Python3

 `# Python3 program to find the cost to remove all array elements``# after performing the specified operations.` `# Function to find the cost to remove all array elements`  `def` `findCost(arr):``    ``# using long to avoid overflow``    ``cost ``=` `0``    ``# loop until array arr is not empty``    ``while` `arr:``        ``# find the maximum element``        ``max_elem ``=` `max``(arr)` `        ``# add it to the cost``        ``cost ``+``=` `max_elem` `        ``# remove it from the array``        ``arr.remove(max_elem)` `        ``# reduce all remaining array elements by 1``        ``for` `i ``in` `range``(``len``(arr)):``            ``arr[i] ``-``=` `1` `        ``# remove all elements reducing to 0``        ``arr ``=` `[x ``for` `x ``in` `arr ``if` `x !``=` `0``]` `    ``# Return the total cost``    ``return` `cost`  `# Driver code``if` `__name__ ``=``=` `'__main__'``:``    ``# Input array``    ``arr ``=` `[``1``, ``6``, ``7``, ``4``, ``2``, ``5``, ``3``]``    ``# Function Call``    ``cost ``=` `findCost(arr)``    ``print``(cost)`

## C#

 `// C# program to find the cost to remove all array elements``// after performing the specified operations.` `using` `System;``using` `System.Collections.Generic;``using` `System.Linq;` `class` `GFG {``    ``// Function to find the cost to remove all array elements``    ``static` `int` `FindCost(List<``int``> arr, ``int` `n) {``        ``// using long to avoid overflow``        ``long` `cost = 0;` `        ``// loop until array arr is not empty``        ``while` `(arr.Count > 0) {``            ``// find the maximum element``            ``int` `max_elem = arr.Max();` `            ``// add it to the cost``            ``cost += max_elem;` `            ``// remove it from the array``            ``arr.Remove(max_elem);` `            ``// reduce all remaining array elements by 1``            ``for` `(``int` `i = 0; i < arr.Count; i++) {``                ``arr[i]--;``            ``}` `            ``// remove all elements reducing to 0``            ``arr.RemoveAll(elem => elem == 0);``        ``}` `        ``// Return the total cost``        ``return` `(``int``) cost;``    ``}``    ` `      ``// Driver's code``    ``static` `void` `Main(``string``[] args) {``        ``// Input array``        ``List<``int``> arr = ``new` `List<``int``>() { 1, 6, 7, 4, 2, 5, 3 };``        ``int` `n = arr.Count;` `        ``// Function Call``        ``int` `cost = FindCost(arr, n);``        ``Console.WriteLine(cost);``    ``}``}`

## Javascript

 `// Function to find the cost to remove all array elements``function` `findCost(arr) {``    ``// using long long to avoid overflow``    ``let cost = 0;` `    ``// loop until array arr is not empty``    ``while` `(arr.length > 0) {``        ``// find the maximum element``        ``let max_elem = Math.max(...arr);` `        ``// add it to the cost``        ``cost += max_elem;``        ``// remove it from the array``        ``arr.splice(arr.indexOf(max_elem), 1);``        ``// reduce all remaining array elements by 1``        ``for` `(let i = 0; i < arr.length; i++) {``            ``arr[i]--;``        ``}``        ``// remove all elements reducing to 0``        ``arr = arr.filter(item => item !== 0);``    ``}` `    ``// Return the total cost``    ``return` `cost;``}` `// Input array``let arr = [1, 6, 7, 4, 2, 5, 3];` `// Function Call``let cost = findCost(arr);``console.log(cost);`

Output

`16`

Time Complexity: O(N2), where N is the size of the given array.
Auxiliary Space: O(1)

Efficient Approach: To optimize the above approach, the idea is to observe that every ith greatest element in the array is added arr[i] – i times to the cost where i is the index of each element arr[i]. Follow the below steps to solve the above problem:

1. Sort the given array in decreasing order.
2. Traverse the array and add the value arr[i] – i for each array element to cost if it is greater than 0.
3. Once the above steps are completed, print the value of cost.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach``#include ``using` `namespace` `std;` `// Function to find the total cost``// of removing all array elements``int` `findCost(``int``* a, ``int` `n)``{``    ``// Sort the array in descending order``    ``sort(a, a + n, greater<``int``>());` `    ``// Stores the total cost``    ``int` `count = 0;` `    ``for` `(``int` `j = 0; j < n; j++) {` `        ``// Contribution of i-th``        ``// greatest element to the cost``        ``int` `p = a[j] - j;` `        ``// Remove the element``        ``a[j] = 0;` `        ``// If negative``        ``if` `(p < 0) {``            ``p = 0;``            ``continue``;``        ``}` `        ``// Add to the final cost``        ``count += p;``    ``}` `    ``// Return the cost``    ``return` `count;``}` `// Driver Code``int` `main()``{``    ``// Given array arr[]``    ``int` `arr[] = { 1, 6, 7, 4, 2, 5, 3 };` `    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr[0]);` `    ``// Function Call``    ``cout << findCost(arr, N);` `    ``return` `0;``}`

## Java

 `// Java program for the above approach``import` `java.util.*;``class` `GFG{` `// Function to find the total cost``// of removing all array elements``static` `int` `findCost(Integer [] a, ``int` `n)``{``    ``// Sort the array in descending order``     ``Arrays.sort(a, Collections.reverseOrder());` `    ``// Stores the total cost``    ``int` `count = ``0``;` `    ``for` `(``int` `j = ``0``; j < n; j++)``    ``{``        ``// Contribution of i-th``        ``// greatest element to the cost``        ``int` `p = a[j] - j;` `        ``// Remove the element``        ``a[j] = ``0``;` `        ``// If negative``        ``if` `(p < ``0``)``        ``{``            ``p = ``0``;``            ``continue``;``        ``}` `        ``// Add to the final cost``        ``count += p;``    ``}` `    ``// Return the cost``    ``return` `count;``}` `// Driver Code``public` `static` `void` `main(String[] args)``{``    ``// Given array arr[]``    ``Integer arr[] = {``1``, ``6``, ``7``,``                     ``4``, ``2``, ``5``, ``3``};` `    ``int` `N = arr.length;` `    ``// Function Call``    ``System.out.print(findCost(arr, N));``}``}` `// This code is contributed by Rajput-Ji`

## Python3

 `# Python3 program for the above approach` `# Function to find the total cost``# of removing all array elements``def` `findCost(a, n):` `    ``# Sort the array in descending order``    ``a.sort(reverse ``=` `True``)` `    ``# Stores the total cost``    ``count ``=` `0` `    ``for` `j ``in` `range``(n):` `        ``# Contribution of i-th``        ``# greatest element to the cost``        ``p ``=` `a[j] ``-` `j` `        ``# Remove the element``        ``a[j] ``=` `0` `        ``# If negative``        ``if``(p < ``0``):``            ``p ``=` `0``            ``continue` `        ``# Add to the final cost``        ``count ``+``=` `p` `    ``# Return the cost``    ``return` `count` `# Driver Code` `# Given array arr[]``arr ``=` `[ ``1``, ``6``, ``7``, ``4``, ``2``, ``5``, ``3` `]` `N ``=` `len``(arr)` `# Function call``print``(findCost(arr, N))` `# This code is contributed by Shivam Singh`

## C#

 `// C# program for the above approach``using` `System;``class` `GFG{` `// Function to find the total cost``// of removing all array elements``static` `int` `findCost(``int` `[]a, ``int` `n)``{``    ``// Sort the array in descending order``    ``Array.Sort(a);``    ``Array.Reverse(a);` `    ``// Stores the total cost``    ``int` `count = 0;` `    ``for` `(``int` `j = 0; j < n; j++)``    ``{``        ``// Contribution of i-th``        ``// greatest element to the cost``        ``int` `p = a[j] - j;` `        ``// Remove the element``        ``a[j] = 0;` `        ``// If negative``        ``if` `(p < 0)``        ``{``            ``p = 0;``            ``continue``;``        ``}` `        ``// Add to the readonly cost``        ``count += p;``    ``}` `    ``// Return the cost``    ``return` `count;``}` `// Driver Code``public` `static` `void` `Main(String[] args)``{``    ``// Given array []arr``    ``int` `[]arr = {1, 6, 7,``                 ``4, 2, 5, 3};` `    ``int` `N = arr.Length;` `    ``// Function Call``    ``Console.Write(findCost(arr, N));``}``}` `// This code is contributed by shikhasingrajput`

## Javascript

 `// JavaScript program for the above approach``// Function to find the total cost``// of removing all array elements``function` `findCost(a, n)``{` `  ``// Sort the array in descending order``  ``a.sort((x, y) => y - x);``  ` `  ``// Stores the total cost``  ``var` `count = 0;` `  ``for` `(``var` `j = 0; j < n; j++)``  ``{``  ` `    ``// Contribution of i-th``    ``// greatest element to the cost``    ``var` `p = a[j] - j;` `    ``// Remove the element``    ``a[j] = 0;` `    ``// If negative``    ``if` `(p < 0) {``      ``p = 0;``      ``continue``;``    ``}``    ` `    ``// Add to the final cost``    ``count += p;``  ``}``  ` `  ``// Return the cost``  ``return` `count;``}` `// Driver Code``// Given array arr[]``var` `arr = [1, 6, 7, 4, 2, 5, 3];``var` `N = arr.length;` `// Function Call``console.log(findCost(arr, N));`

Output

`16`

Time Complexity: O(NlogN), where N is the size of the given array.
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up