# 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 = 6

Input: arr[] = { 1, 4, 3, 5, 6 ,13, 10}
Output: 4
Explanation: The subarray from  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 ` `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 m1 = ``new` `TreeSet();` `    ``SortedSet m2 = ``new` `TreeSet();`   `    ``// 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

 ``

Output

`6`

Time Complexity: O(N * logN )
Auxiliary Space: O(N)

Method 2:

Problem: Given an array A consisting of N integers, the task is to find the minimum cost to sort the array in increasing order and we can perform the following operation any number of times such that:

• Choose a continuous subarray A[L, R] and sort the array in increasing order, while keeping other elements unchanged. The cost to perform this operation is max(AL…R) − min(AL…R).

Examples:

Input: S = {10, 1, 4}
Output: 9
Explanation: We can apply the operation on A[1…3] which converts A into [1, 4, 10] which is sorted in increasing order. So, the total cost is 10 − 1 = 9. It can be shown that we can’t sort A with less than 9 total cost.

Input: S = {3, 1, 3, 3, 4, 3}
Output: 3

Approach: The problem can be solved based on the following observation:

• The most basic solution would be a single operation where the whole array is covered. It’d cost max(A) − min(A) and sorts the array immediately. So we always have a solution to sort the array.
• Secondly, we can observe that if there are two operations A[l1…r1] and A[l2…r2], where intervals [l1, r1] and [l2, r2] even share an endpoint, applying one operation on range [min(l1, l2) ,max(r1, r2)] is sufficient to sort the both subarray, with lower cost. Hence, no position might be covered in more than one operation.
• Now, the task becomes to partition A into continuous partitions, where the operation would be applied on each partition once. The partitions would be chosen so as to maximize the number of partitions while ensuring that once all partitions are sorted, A becomes sorted.
•  For example, for A = [1, 2, 5, 6, 4, 3, 7, 9, 8], we can partition it like {, , [5, 6, 4, 3], , [9, 8]} and apply operation on each partition, leading to {, , [3, 4, 5, 6], , [8, 9]} in cost 6 − 3 + 9 − 8 = 4.
• In order to find these partitions, we need to find for each x, whether the first x elements in A form the same multiset as the smallest x elements of A. In the above example, positions satisfying that condition are 1, 2, 6, 7, 9 each of which forms a partition ending at that position.

Below is the implementation of the above approach:

## C++

 `// C++ code to implement the approach` `#include ` `using` `namespace` `std;`   `// Function to find minimum cost` `// to sort the array` `void` `minCost(``int` `array[], ``int` `n)` `{` `  ``int``* max = ``new` `int``[n];` `  ``int``* min = ``new` `int``[n];` `  ``min[n - 1] = array[n - 1];` `  ``int` `temp = array[n - 1];` `  ``max = array;`   `  ``for` `(``int` `i = n - 2; i >= 0; i--) {` `    ``if` `(array[i] < temp) {` `      ``temp = array[i];` `    ``}` `    ``min[i] = temp;` `  ``}` `  ``temp = array;`   `  ``for` `(``int` `i = 1; i < n; i++) {` `    ``if` `(array[i] > temp) {` `      ``temp = array[i];` `    ``}` `    ``max[i] = temp;` `  ``}`   `  ``int` `ans = 0;` `  ``int` `l = 0;` `  ``int` `r = 0;`   `  ``for` `(``int` `i = 0; i < n - 1; i++) {` `    ``if` `(max[i] <= min[i + 1]) {` `      ``r = i;` `      ``int` `p = max[r] - min[l];` `      ``ans += p;`   `      ``l = r + 1;` `    ``}` `  ``}` `  ``ans += max[n - 1] - min[l];`   `  ``cout << ans << endl;` `}`   `// Driver Code` `int` `main()` `{` `  ``int` `N = 6;` `  ``int` `A[] = { 1, 8, 5, 2, 1, 7 };`   `  ``// Function Call` `  ``minCost(A, N);` `}`   `// This code is contributed by garg28harsh.`

## Java

 `// Java code to implement the approach`   `import` `java.io.*;` `import` `java.util.*;`   `public` `class` `GFG {`   `    ``// Function to find minimum cost` `    ``// to sort the array` `    ``public` `static` `void` `minCost(``int` `array[], ``int` `n)` `    ``{` `        ``int``[] max = ``new` `int``[n];` `        ``int``[] min = ``new` `int``[n];` `        ``min[n - ``1``] = array[n - ``1``];` `        ``int` `temp = array[n - ``1``];` `        ``max[``0``] = array[``0``];`   `        ``for` `(``int` `i = n - ``2``; i >= ``0``; i--) {` `            ``if` `(array[i] < temp) {` `                ``temp = array[i];` `            ``}` `            ``min[i] = temp;` `        ``}` `        ``temp = array[``0``];`   `        ``for` `(``int` `i = ``1``; i < n; i++) {` `            ``if` `(array[i] > temp) {` `                ``temp = array[i];` `            ``}` `            ``max[i] = temp;` `        ``}`   `        ``int` `ans = ``0``;` `        ``int` `l = ``0``;` `        ``int` `r = ``0``;`   `        ``for` `(``int` `i = ``0``; i < n - ``1``; i++) {` `            ``if` `(max[i] <= min[i + ``1``]) {` `                ``r = i;` `                ``int` `p = max[r] - min[l];` `                ``ans += p;`   `                ``l = r + ``1``;` `            ``}` `        ``}` `        ``ans += max[n - ``1``] - min[l];`   `        ``System.out.println(ans);` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``int``[] A = { ``1``, ``8``, ``5``, ``2``, ``1``, ``7` `};` `        ``int` `N = A.length;`   `        ``// Function Call` `        ``minCost(A, N);` `    ``}` `}`

## Python3

 `# Python code to implement the approach`   `# Function to find minimum cost` `# to sort the array`     `def` `minCost(array, n):` `    ``max` `=` `[``0``]``*``n` `    ``min` `=` `[``0``]``*``n` `    ``min``[n ``-` `1``] ``=` `array[n ``-` `1``]` `    ``temp ``=` `array[n ``-` `1``]` `    ``max``[``0``] ``=` `array[``0``]` `    ``for` `i ``in` `range``(n``-``2``, ``-``1``, ``-``1``):` `        ``if` `(array[i] < temp):` `            ``temp ``=` `array[i]` `        ``min``[i] ``=` `temp` `    ``temp ``=` `array[``0``]` `    ``for` `i ``in` `range``(``1``, n):` `        ``if` `(array[i] > temp):` `            ``temp ``=` `array[i]` `        ``max``[i] ``=` `temp`   `    ``ans ``=` `0` `    ``l ``=` `0` `    ``r ``=` `0` `    ``for` `i ``in` `range``(n``-``1``):` `        ``if` `(``max``[i] <``=` `min``[i ``+` `1``]):` `            ``r ``=` `i` `            ``p ``=` `max``[r] ``-` `min``[l]` `            ``ans ``+``=` `p` `            ``l ``=` `r ``+` `1`   `    ``ans ``+``=` `max``[n ``-` `1``] ``-` `min``[l]`   `    ``print``(ans)`     `# Driver Code` `A ``=` `[``1``, ``8``, ``5``, ``2``, ``1``, ``7``]` `N ``=` `len``(A)`   `# Function Call` `minCost(A, N)`   `# This code is contributed by vikkycirus.`

## C#

 `// C# code to implement the approach` `using` `System;` `using` `System.Collections.Generic;`   `public` `class` `GFG {`   `  ``// Function to find minimum cost` `  ``// to sort the array` `  ``static` `void` `minCost(``int``[] array, ``int` `n)` `  ``{` `    ``int``[] max = ``new` `int``[n];` `    ``int``[] min = ``new` `int``[n];` `    ``min[n - 1] = array[n - 1];` `    ``int` `temp = array[n - 1];` `    ``max = array;`   `    ``for` `(``int` `i = n - 2; i >= 0; i--) {` `      ``if` `(array[i] < temp) {` `        ``temp = array[i];` `      ``}` `      ``min[i] = temp;` `    ``}` `    ``temp = array;`   `    ``for` `(``int` `i = 1; i < n; i++) {` `      ``if` `(array[i] > temp) {` `        ``temp = array[i];` `      ``}` `      ``max[i] = temp;` `    ``}`   `    ``int` `ans = 0;` `    ``int` `l = 0;` `    ``int` `r = 0;`   `    ``for` `(``int` `i = 0; i < n - 1; i++) {` `      ``if` `(max[i] <= min[i + 1]) {` `        ``r = i;` `        ``int` `p = max[r] - min[l];` `        ``ans += p;`   `        ``l = r + 1;` `      ``}` `    ``}` `    ``ans += max[n - 1] - min[l];`   `    ``Console.Write(ans);` `  ``}`   `  ``// Driver code` `  ``public` `static` `void` `Main(``string``[] args)` `  ``{` `    ``int` `N = 6;` `    ``int``[] A = { 1, 8, 5, 2, 1, 7 };`   `    ``// Function Call` `    ``minCost(A, N);` `  ``}` `}`   `// This code is contributed by garg28harsh.`

## Javascript

 `// Javascript code to implement the approach`   `// Function to find minimum cost` `// to sort the array` `function` `minCost(array, n) {` `    ``let max = ``new` `Array(n);` `    ``let min = ``new` `Array(n);` `    ``min[n - 1] = array[n - 1];` `    ``let temp = array[n - 1];` `    ``max = array;`   `    ``for` `(let i = n - 2; i >= 0; i--) {` `        ``if` `(array[i] < temp) {` `            ``temp = array[i];` `        ``}` `        ``min[i] = temp;` `    ``}` `    ``temp = array;`   `    ``for` `(let i = 1; i < n; i++) {` `        ``if` `(array[i] > temp) {` `            ``temp = array[i];` `        ``}` `        ``max[i] = temp;` `    ``}`   `    ``let ans = 0;` `    ``let l = 0;` `    ``let r = 0;`   `    ``for` `(let i = 0; i < n - 1; i++) {` `        ``if` `(max[i] <= min[i + 1]) {` `            ``r = i;` `            ``let p = max[r] - min[l];` `            ``ans += p;`   `            ``l = r + 1;` `        ``}` `    ``}` `    ``ans += max[n - 1] - min[l];`   `    ``console.log(ans);` `}`   `// Driver Code` `let A = [1, 8, 5, 2, 1, 7];` `let N = A.length;`   `// Function Call` `minCost(A, N);`   `// This code is contributed by saurabh_jaiswal. `

Output

`7`

Time Complexity: O(N)
Auxiliary Space: O(N)

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Previous
Next