VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimize-cost-required-to-complete-all-processes/

⇱ Minimize cost required to complete all processes - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimize cost required to complete all processes

Last Updated : 3 Oct, 2025

Given a 2D array arr[][] with each row of the form { X, Y }, where Y and X represents the minimum cost required to initiate a process and the total cost spent to complete the process respectively. The task is to find the minimum cost required to complete all the process of the given array if processes can be completed in any order.

Examples:

Input: arr[][] = { { 1, 2 }, { 2, 4 }, { 4, 8 } } 
Output:
Explanation: 
Consider an initial cost of 8. 
Initiate the process arr[2] and after finishing the process, remaining cost = 8 - 4 = 4 
Initiate the process arr[1] and after finishing the process, remaining cost = 4 - 2 = 2 
Initiate the process arr[0] and after finishing the process, remaining cost = 2 - 1 = 1 
Therefore, the required output is 8.

Input: arr[][] = { { 1, 7 }, { 2, 8 }, { 3, 9 }, { 4, 10 }, { 5, 11 }, { 6, 12 } } 
Output: 27

Approach: The problem can be solved using Greedy technique. Follow the steps below to solve the problem:

  • Sort the array in descending order of Y.
  • Initialize a variable, say minCost, to store the minimum cost required to complete all the process.
  • Initialize a variable, say minCostInit, to store the minimum cost to initiate a process.
  • Traverse the array using variable i. For every ith iteration, check if minCostInit is less than arr[i][1] or not. If found to be true then increment the value of minCost by (arr[i][1] - minCostInit) and update minCostInit = arr[i][1].
  • In every ith iteration also update the value of minCostInit -= arr[i][0].
  • Finally, print the value of minCost.

Below is the implementation of the above approach.


Output: 
8

 

Time Complexity: O(N * log(N)) 
Auxiliary Space: O(1)

Comment
Article Tags: