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++
#include <bits/stdc++.h>
using namespace std;
int minimum_cost(vector< int > arr)
{
vector< int > sorted = arr;
int n = arr.size();
sort(sorted.begin(), sorted.end());
multiset< int > m1, m2;
int cost = 0;
for ( int i = 0; i < n; i++) {
if (sorted[i] != arr[i]) {
m1.insert(arr[i]);
m2.insert(sorted[i]);
if (m1 == m2) {
cost += (*m1.rbegin() -
*m2.begin());
m1.clear();
m2.clear();
}
}
}
return cost;
}
int main()
{
vector< int > arr = { 1, 7, 5, 2, 1, 8 };
cout << minimum_cost(arr);
return 0;
}
|
Java
import java.util.*;
class GFG {
public static int minimum_cost( int [] arr)
{
int n = arr.length;
int [] sorted = new int [n];
sorted = arr.clone();
Arrays.sort(sorted);
SortedSet<Integer> m1 = new TreeSet<Integer>();
SortedSet<Integer> m2 = new TreeSet<Integer>();
int cost = 0 ;
for ( int i = 0 ; i < n; i++) {
if (sorted[i] != arr[i]) {
m1.add(arr[i]);
m2.add(sorted[i]);
if (m1.equals(m2))
{
cost += (Collections.max(m1) - Collections.min(m2));
m1.clear();
m2.clear();
}
}
}
return cost;
}
public static void main (String[] args)
{
int [] arr = { 1 , 7 , 5 , 2 , 1 , 8 };
System.out.println(minimum_cost(arr));
}
}
|
Python3
def minimum_cost(arr):
sorted = arr.copy()
n = len (arr)
sorted .sort()
m1 = set ()
m2 = set ()
cost = 0
for i in range ( 0 , n):
if ( sorted [i] ! = arr[i]):
m1.add(arr[i])
m2.add( sorted [i])
if (m1 = = m2):
cost + = ( list (m1)[ len ( list (m1)) - 1 ] -
list (m2)[ 0 ])
m1.clear()
m2.clear()
return cost
if __name__ = = "__main__" :
arr = [ 1 , 7 , 5 , 2 , 1 , 8 ]
print (minimum_cost(arr))
|
C#
using System;
using System.Collections.Generic;
public class GFG{
public static int minimum_cost( int [] arr)
{
int n = arr.Length;
int [] sorted = new int [n];
Array.Copy(arr, 0, sorted, 0, n);
Array.Sort(sorted);
SortedSet< int > m1 = new SortedSet< int >();
SortedSet< int > m2 = new SortedSet< int >();
int cost = 0;
for ( int i = 0; i < n; i++) {
if (sorted[i] != arr[i]) {
m1.Add(arr[i]);
m2.Add(sorted[i]);
if (m1.SetEquals(m2))
{
cost += (m1.Max - m2.Min);
m1.Clear();
m2.Clear();
}
}
}
return cost;
}
public static void Main()
{
int [] arr = { 1, 7, 5, 2, 1, 8 };
Console.Write(minimum_cost(arr));
}
}
|
Javascript
<script>
function minimum_cost(arr)
{
var sorted = arr.slice();
var n = arr.length;
sorted.sort();
var m1 = new Set();
var m2 = new Set();
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 (areSetsEqual(m1,m2)) {
cost += (Math.max(...Array.from(m1.values())) -
Math.min(...Array.from(m2.values())));
m1.clear();
m2.clear();
}
}
}
return cost;
}
var arr = [ 1, 7, 5, 2, 1, 8 ];
document.write(minimum_cost(arr));
</script>
|
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 {[1], [2], [5, 6, 4, 3], [7], [9, 8]} and apply operation on each partition, leading to {[1], [2], [3, 4, 5, 6], [7], [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++
#include <bits/stdc++.h>
using namespace std;
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];
cout << ans << endl;
}
int main()
{
int N = 6;
int A[] = { 1, 8, 5, 2, 1, 7 };
minCost(A, N);
}
|
Java
import java.io.*;
import java.util.*;
public class GFG {
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);
}
public static void main(String[] args)
{
int [] A = { 1 , 8 , 5 , 2 , 1 , 7 };
int N = A.length;
minCost(A, N);
}
}
|
Python3
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)
A = [ 1 , 8 , 5 , 2 , 1 , 7 ]
N = len (A)
minCost(A, N)
|
C#
using System;
using System.Collections.Generic;
public class GFG {
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];
Console.Write(ans);
}
public static void Main( string [] args)
{
int N = 6;
int [] A = { 1, 8, 5, 2, 1, 7 };
minCost(A, N);
}
}
|
Javascript
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[0] = array[0];
for (let i = n - 2; i >= 0; i--) {
if (array[i] < temp) {
temp = array[i];
}
min[i] = temp;
}
temp = array[0];
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);
}
let A = [1, 8, 5, 2, 1, 7];
let N = A.length;
minCost(A, N);
|
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!
Last Updated :
13 Dec, 2022
Like Article
Save Article