Minimize cost to sort given array by sorting unsorted subarrays
Given an array arr[] of size N, the task is to minimize the cost to sort the array by sorting any unsorted subarray where the cost of the operation is the difference between the maximum and minimum element of that subarray. This operation can be performed infinite times including 0.
Examples:
Input: arr[] = {1, 7, 5, 2, 1, 8}
Output: 6
Explanation: The subarray from index [1,4] can be chosen and can be sorted with cost = 7 – 1 = 6Input: arr[] = { 1, 4, 3, 5, 6 ,13, 10}
Output: 4
Explanation: The subarray from index index [1,2] and [5,6] can be sorted with cost of 4 – 3 and 13 – 10 = 1 + 3 = 4
Approach: This can be solved using the greedy approach, the elements already sorted don’t require any cost so only the subarrays that have unsorted elements must be considered to sort. Multiset can be used to store the elements that are not in sorted order and the difference between the last and first element of multiset gives the cost.
Follow these steps to solve the above problem:
- Initialize a vector v and copy the arr into it and assign the size of the vector to the variable n.
- Now sort the vector v.
- Initialize 2 multisets m1 and m2 to store the unsorted and sorted subarray respectively and cost = 0 to store the result.
- Now iterate through the range [0,N) and check
- If v[i] is not equal to arr[i]
- Insert arr[i] into m1 and v[i] into m2
- When both the multisets are the same add the difference between the last and first element of the set to the cost.
- Clear both the multisets to make them used by the next unsorted subarray.
- Print the 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 minimum cost // to sort the array in ascending order int minimum_cost(vector< int > arr) { // Copy the arr into vector and sort it vector< int > sorted = arr; int n = arr.size(); sort(sorted.begin(), sorted.end()); // Initialize the two multisets to store // sorted and the unordered elements multiset< int > m1, m2; // Initialize cost to store final answer int cost = 0; for ( int i = 0; i < n; i++) { if (sorted[i] != arr[i]) { m1.insert(arr[i]); m2.insert(sorted[i]); // If both the multisets are equal, // the unordered subarray is sorted if (m1 == m2) { // The cost is difference // between mini and max cost += (*m1.rbegin() - *m2.begin()); // Clear the multisets to make // use of it again m1.clear(); m2.clear(); } } } return cost; } // Driver code int main() { // Initialize the queries vector< int > arr = { 1, 7, 5, 2, 1, 8 }; cout << minimum_cost(arr); return 0; } |
Java
// Java code to implement the above approach import java.util.*; class GFG { // Function to find the minimum cost // to sort the array in ascending order public static int minimum_cost( int [] arr) { // Copy the arr into vector and sort it int n = arr.length; int [] sorted = new int [n]; sorted = arr.clone(); Arrays.sort(sorted); // Initialize the two multisets to store // sorted and the unordered elements SortedSet<Integer> m1 = new TreeSet<Integer>(); SortedSet<Integer> m2 = new TreeSet<Integer>(); // Initialize cost to store final answer int cost = 0 ; for ( int i = 0 ; i < n; i++) { if (sorted[i] != arr[i]) { m1.add(arr[i]); m2.add(sorted[i]); // If both the multisets are equal, // the unordered subarray is sorted if (m1.equals(m2)) { // The cost is difference // between mini and max cost += (Collections.max(m1) - Collections.min(m2)); // Clear the multisets to make // use of it again m1.clear(); m2.clear(); } } } return cost; } // Driver code public static void main (String[] args) { // Initialize the queries int [] arr = { 1 , 7 , 5 , 2 , 1 , 8 }; System.out.println(minimum_cost(arr)); } } // This code is contributed by Shubham Singh |
Python3
# python3 program for the above approach # Function to find the minimum cost # to sort the array in ascending order def minimum_cost(arr): # Copy the arr into vector and sort it sorted = arr.copy() n = len (arr) sorted .sort() # Initialize the two multisets to store # sorted and the unordered elements m1 = set () m2 = set () # Initialize cost to store final answer cost = 0 for i in range ( 0 , n): if ( sorted [i] ! = arr[i]): m1.add(arr[i]) m2.add( sorted [i]) # If both the multisets are equal, # the unordered subarray is sorted if (m1 = = m2): # The cost is difference # between mini and max cost + = ( list (m1)[ len ( list (m1)) - 1 ] - list (m2)[ 0 ]) # Clear the multisets to make # use of it again m1.clear() m2.clear() return cost # Driver code if __name__ = = "__main__" : # Initialize the queries arr = [ 1 , 7 , 5 , 2 , 1 , 8 ] print (minimum_cost(arr)) # This code is contributed by rakeshsahni |
C#
// C# code to implement the above approach using System; using System.Collections.Generic; public class GFG{ // Function to find the minimum cost // to sort the array in ascending order public static int minimum_cost( int [] arr) { // Copy the arr into vector and sort it int n = arr.Length; int [] sorted = new int [n]; Array.Copy(arr, 0, sorted, 0, n); Array.Sort(sorted); // Initialize the two multisets to store // sorted and the unordered elements SortedSet< int > m1 = new SortedSet< int >(); SortedSet< int > m2 = new SortedSet< int >(); // Initialize cost to store final answer int cost = 0; for ( int i = 0; i < n; i++) { if (sorted[i] != arr[i]) { m1.Add(arr[i]); m2.Add(sorted[i]); // If both the multisets are equal, // the unordered subarray is sorted if (m1.SetEquals(m2)) { // The cost is difference // between mini and max cost += (m1.Max - m2.Min); // Clear the multisets to make // use of it again m1.Clear(); m2.Clear(); } } } return cost; } // Driver code public static void Main() { // Initialize the queries int [] arr = { 1, 7, 5, 2, 1, 8 }; Console.Write(minimum_cost(arr)); } } // This code is contributed by Shubham Singh |
Javascript
<script> // Javascript program for the above approach // Function to find the minimum cost // to sort the array in ascending order function minimum_cost(arr) { // Copy the arr into vector and sort it var sorted = arr.slice(); var n = arr.length; sorted.sort(); // Initialize the two multisets to store // sorted and the unordered elements var m1 = new Set(); var m2 = new Set(); // Initialize cost to store final answer var cost = 0; let areSetsEqual = (a, b) => a.size === b.size && [...a].every(value => b.has(value)); for ( var i = 0; i < n; i++) { if (sorted[i] != arr[i]) { m1.add(arr[i]); m2.add(sorted[i]); // If both the multisets are equal, // the unordered subarray is sorted if (areSetsEqual(m1,m2)) { // The cost is difference // between mini and max cost += (Math.max(...Array.from(m1.values())) - Math.min(...Array.from(m2.values()))); // Clear the multisets to make // use of it again m1.clear(); m2.clear(); } } } return cost; } // Driver code // Initialize the queries var arr = [ 1, 7, 5, 2, 1, 8 ]; document.write(minimum_cost(arr)); // This code is contributed by Shubham Singh </script> |
6
Time Complexity: O(N * logN )
Auxiliary Space: O(N)