Skip to content
Related Articles

Related Articles

Cost required to empty a given array by repeated removal of maximum obtained by given operations
  • Last Updated : 06 May, 2021

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.

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 <bits/stdc++.h>
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




<script>
      // 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
      document.write(findCost(arr, N));
    </script>
Output: 
16

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

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :