Given an array arr[] of N positive integers, the task is to find the minimum cost to sort the given array by moving an array element to any position such that the cost of moving that element is the value of that element.
Examples:
Input: arr[] = {7, 1, 2, 3}
Output: 6
Explanation:
Following are the possible set of moves to sort the array with minimum cost:
- Move 1 to the front, arr[] = {1, 7, 2, 3}. cost = 1
- Move 2 to 2nd place, arr[] = {1, 2, 7, 3}. cost = 2
- Move 3 to 3rd place, arr[] = {1, 2, 3, 7}, cost = 3
Therefore, the total cost is (1 + 2 + 3) = 6.
Input: arr[] = {7, 1, 2, 5}
Output: 7
Approach: The given problem can be solved by using Dynamic Programming. The idea is to fixed the array elements that forms the longest non-decreasing subsequence having the maximum sum and perform the given moves to all the remaining array elements. Follow the below steps to solve the problem:
- Find the longest non-decreasing subsequence with the maximal sum and store it in a variable, say S.
- After the above step, print the value of the (sum of array element – S) as the resultant possible minimum cost of sorting the given array.
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 maximum sum of// non-decreasing subsequenceint maxSumIS(int arr[], int n){    int i, j, max = 0;    // Stores the maximum sum of subsequence ending at index i    int dp[n];    // Initialize dp[] values for all indexes    for (i = 0; i < n; i++)        dp[i] = arr[i];Â
    // Compute maximum sum values in bottom up manner    for (i = 1; i < n; i++)        for (j = 0; j < i; j++)            if (arr[i] >= arr[j] && dp[i] < dp[j] + arr[i])                dp[i] = dp[j] + arr[i];Â
    // Pick maximum of all msis values    for (i = 0; i < n; i++)        if (max < dp[i])            max = dp[i];Â
    // Return the maximum sum as max    return max;}Â
// Function to find the minimum cost to// sort given array in increasing orderint minCostSort(int arr[], int N){    // Find the sum of array    int sm = 0;    for (int i = 0; i < N; i++)        sm += arr[i];    // Find the maximum sum non-decreasing subsequence    int res = maxSumIS(arr, N);    // Return the minimum cost    return sm - res;}Â
// Driver Codeint main(){Â Â Â Â int arr[] = { 7, 1, 2, 3 };Â Â Â Â int N = sizeof(arr) / sizeof(arr[0]);Â Â Â Â cout << minCostSort(arr, N);Â Â Â Â return 0;}Â
// This code is contributed by Sania Kumari Gupta |
C
// C program for the above approach#include <stdio.h>Â
// Function to find the maximum sum of non-decreasing// subsequenceint maxSumIS(int arr[], int n){    int i, j, max = 0;    // Stores the maximum sum of subsequence ending at index i    int dp[n];    // Initialize dp[] values for all indexes    for (i = 0; i < n; i++)        dp[i] = arr[i];Â
    // Compute maximum sum values in bottom up manner    for (i = 1; i < n; i++)        for (j = 0; j < i; j++)            if (arr[i] >= arr[j] && dp[i] < dp[j] + arr[i])                dp[i] = dp[j] + arr[i];Â
    // Pick maximum of all msis values    for (i = 0; i < n; i++)        if (max < dp[i])            max = dp[i];Â
    // Return the maximum sum as max    return max;}Â
// Function to find the minimum cost to// sort given array in increasing orderint minCostSort(int arr[], int N){    // Find the sum of array    int sm = 0;    for (int i = 0; i < N; i++)        sm += arr[i];    // Find the maximum sum non-decreasing subsequence    int res = maxSumIS(arr, N);Â
    // Return the minimum cost    return sm - res;}Â
// Driver Codeint main(){Â Â Â Â int arr[] = { 7, 1, 2, 3 };Â Â Â Â int N = sizeof(arr) / sizeof(arr[0]);Â Â Â Â printf("%d", minCostSort(arr, N));Â Â Â Â return 0;}Â
// This code is contributed by Sania Kumari Gupta |
Java
// Java program for the above approachimport java.io.*;class GFG {       // Function to find the maximum sum of    // non-decreasing subsequence    static int maxSumIS(int[] arr, int n)    {        int i, j, max = 0;Â
        // Stores the maximum sum of        // subsequence ending at index i        int[] dp = new int[n];Â
        // Initialize dp[] values for all        // indexes        for (i = 0; i < n; i++)            dp[i] = arr[i];Â
        // Compute maximum sum values        // in bottom up manner        for (i = 1; i < n; i++)            for (j = 0; j < i; j++)                if (arr[i] >= arr[j]                    && dp[i] < dp[j] + arr[i])                    dp[i] = dp[j] + arr[i];Â
        // Pick maximum of all msis values        for (i = 0; i < n; i++) {            if (max < dp[i]) {                max = dp[i];            }        }Â
        // Return the maximum sum as max        return max;    }Â
    // Function to find the minimum cost to    // sort given array in increasing order    static int minCostSort(int[] arr, int N)    {        // Find the sum of array        int sm = 0;        for (int i = 0; i < N; i++) {            sm += arr[i];        }Â
        // Find the maximum sum non-decreasing        // subsequence        int res = maxSumIS(arr, N);Â
        // Return the minimum cost        return sm - res;    }Â
    // Driver Code    public static void main(String []args)    {        int[] arr = { 7, 1, 2, 3 };        int N = arr.length;        System.out.print(minCostSort(arr, N));    }}Â
// This code is contributed by shivanisinghss2110 |
Python3
# python program for the above approachÂ
# Function to find the maximum sum of# non-decreasing subsequencedef maxSumIS(arr, n):Â
    max = 0Â
    # Stores the maximum sum of    # subsequence ending at index i    dp = [0 for _ in range(n)]Â
    # Initialize dp[] values for all    # indexes    for i in range(0, n):        dp[i] = arr[i]Â
    # Compute maximum sum values    # in bottom up manner    for i in range(1, n):        for j in range(0, i):            if (arr[i] >= arr[j] and dp[i] < dp[j] + arr[i]):                dp[i] = dp[j] + arr[i]Â
    # Pick maximum of all msis values    for i in range(0, n):        if (max < dp[i]):            max = dp[i]Â
    # Return the maximum sum as max    return maxÂ
# Function to find the minimum cost to# sort given array in increasing orderdef minCostSort(arr, N):Â
    # Find the sum of array    sm = 0    for i in range(0, N):        sm += arr[i]Â
    # Find the maximum sum non-decreasing    # subsequence    res = maxSumIS(arr, N)Â
    # Return the minimum cost    return sm - resÂ
# Driver Codeif __name__ == "__main__":Â
    arr = [7, 1, 2, 3]    N = len(arr)    print(minCostSort(arr, N))Â
# This code is contributed by rakeshsahni |
C#
// C# program for the above approachusing System;class GFG {       // Function to find the maximum sum of    // non-decreasing subsequence    static int maxSumIS(int[] arr, int n)    {        int i, j, max = 0;Â
        // Stores the maximum sum of        // subsequence ending at index i        int[] dp = new int[n];Â
        // Initialize dp[] values for all        // indexes        for (i = 0; i < n; i++)            dp[i] = arr[i];Â
        // Compute maximum sum values        // in bottom up manner        for (i = 1; i < n; i++)            for (j = 0; j < i; j++)                if (arr[i] >= arr[j]                    && dp[i] < dp[j] + arr[i])                    dp[i] = dp[j] + arr[i];Â
        // Pick maximum of all msis values        for (i = 0; i < n; i++) {            if (max < dp[i]) {                max = dp[i];            }        }Â
        // Return the maximum sum as max        return max;    }Â
    // Function to find the minimum cost to    // sort given array in increasing order    static int minCostSort(int[] arr, int N)    {        // Find the sum of array        int sm = 0;        for (int i = 0; i < N; i++) {            sm += arr[i];        }Â
        // Find the maximum sum non-decreasing        // subsequence        int res = maxSumIS(arr, N);Â
        // Return the minimum cost        return sm - res;    }Â
    // Driver Code    public static void Main()    {        int[] arr = { 7, 1, 2, 3 };        int N = arr.Length;        Console.WriteLine(minCostSort(arr, N));    }}Â
// This code is contributed by ukasp. |
Javascript
<script>       // JavaScript Program to implement       // the above approachÂ
Â
       // Function to find the maximum sum of       // non-decreasing subsequence       function maxSumIS(arr, n) {           let i, j, max = 0;Â
           // Stores the maximum sum of           // subsequence ending at index i           let dp = new Array(n);Â
           // Initialize dp[] values for all           // indexes           for (i = 0; i < n; i++)               dp[i] = arr[i];Â
           // Compute maximum sum values           // in bottom up manner           for (i = 1; i < n; i++)               for (j = 0; j < i; j++)                   if (arr[i] >= arr[j]                       && dp[i] < dp[j] + arr[i])                       dp[i] = dp[j] + arr[i];Â
           // Pick maximum of all msis values           for (i = 0; i < n; i++) {               if (max < dp[i]) {                   max = dp[i];               }           }Â
           // Return the maximum sum as max           return max;       }Â
       // Function to find the minimum cost to       // sort given array in increasing order       function minCostSort(arr, N) {           // Find the sum of array           let sm = 0;           for (let i = 0; i < N; i++) {               sm += arr[i];           }Â
           // Find the maximum sum non-decreasing           // subsequence           let res = maxSumIS(arr, N);Â
           // Return the minimum cost           return sm - res;       }Â
       // Driver Code       let arr = [7, 1, 2, 3];       let N = arr.length;       document.write(minCostSort(arr, N));Â
Â
    // This code is contributed by Potta LokeshÂ
   </script> |
6
Â
Time Complexity: O(N2)
Auxiliary Space: O(N)
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
