Given two arrays arr[] and cost[] where cost[i] is the cost associated with arr[i], the task is to find the minimum cost of choosing three elements from the array such that arr[i] < arr[j] < arr[k].
Examples:
Input: arr[] = {2, 4, 5, 4, 10}, cost[] = {40, 30, 20, 10, 40}
Output: 90
(2, 4, 5), (2, 4, 10) and (4, 5, 10) are
the only valid triplets with cost 90.Input: arr[] = {1, 2, 3, 4, 5, 6}, cost[] = {10, 13, 11, 14, 15, 12}
Output: 33
Naive approach: A basic approach is two-run three nested loops and to check every possible triplet. The time complexity of this approach will be O(n3).
Approach:
- We can use a brute-force approach to iterate over all possible triplets of elements in the array and check if they form an increasing sequence.
- If a triplet forms an increasing sequence, we calculate its cost by adding the costs of its elements.
- We keep track of the minimum cost seen so far and return it as a result.
The array arr, the related costs cost, and the length of the arrays n are passed to the min_cost_triplet method. It iterates through all potential triplets of elements, tests to see if they form an increasing sequence then computes the triplet’s cost. It maintains track of the lowest cost encountered thus far and returns it as the result.
We define the input arrays, determine their length, call the min_cost_triplet function, then print the result in the main function.
Implementation:
C++
| #include <bits/stdc++.h>usingnamespacestd;intmin_cost_triplet(intarr[], intcost[], intn) {    intmin_cost = INT_MAX;    // iterate over all possible triplets of elements    for(inti = 0; i < n - 2; i++) {        for(intj = i + 1; j < n - 1; j++) {            for(intk = j + 1; k < n; k++) {                // check if triplet forms an increasing sequence                if(arr[i] < arr[j] && arr[j] < arr[k]) {                    intcurr_cost = cost[i] + cost[j] + cost[k];                    // update minimum cost seen so far                    if(curr_cost < min_cost) {                        min_cost = curr_cost;                    }                }            }        }    }    // return minimum cost of valid triplets    returnmin_cost;}intmain() {    intarr[] = {2, 4, 5, 4, 10};    intcost[] = {40, 30, 20, 10, 40};    intn = sizeof(arr) / sizeof(arr[0]);    cout << min_cost_triplet(arr, cost, n) << endl;    return0;} | 
Java
| importjava.io.*;importjava.util.Arrays;publicclassGFG {    publicstaticintminCostTriplet(int[] arr, int[] cost, intn) {        intminCost = Integer.MAX_VALUE;        // iterate over all possible triplets of elements        for(inti = 0; i < n - 2; i++) {            for(intj = i + 1; j < n - 1; j++) {                for(intk = j + 1; k < n; k++) {                    // check if triplet forms an increasing sequence                    if(arr[i] < arr[j] && arr[j] < arr[k]) {                        intcurrCost = cost[i] + cost[j] + cost[k];                        // update minimum cost seen so far                        if(currCost < minCost) {                            minCost = currCost;                        }                    }                }            }        }        // return minimum cost of valid triplets        returnminCost;    }    publicstaticvoidmain(String[] args) {        int[] arr = {2, 4, 5, 4, 10};        int[] cost = {40, 30, 20, 10, 40};        intn = arr.length;        System.out.println(minCostTriplet(arr, cost, n));    }} | 
Python
| defmin_cost_triplet(arr, cost, n):    min_cost =float('inf')    # iterate over all possible triplets of elements    fori inrange(n -2):        forj inrange(i +1, n -1):            fork inrange(j +1, n):                # check if triplet forms an increasing sequence                ifarr[i] < arr[j] < arr[k]:                    curr_cost =cost[i] +cost[j] +cost[k]                    # update minimum cost seen so far                    ifcurr_cost < min_cost:                        min_cost =curr_cost    # return minimum cost of valid triplets    returnmin_costarr =[2, 4, 5, 4, 10]cost =[40, 30, 20, 10, 40]n =len(arr)print(min_cost_triplet(arr, cost, n)) | 
C#
| usingSystem;publicclassGFG{    publicstaticintMinCostTriplet(int[] arr, int[] cost, intn)    {        intminCost = int.MaxValue;        // iterate over all possible triplets of elements        for(inti = 0; i < n - 2; i++)        {            for(intj = i + 1; j < n - 1; j++)            {                for(intk = j + 1; k < n; k++)                {                    // check if triplet forms an increasing sequence                    if(arr[i] < arr[j] && arr[j] < arr[k])                    {                        intcurrCost = cost[i] + cost[j] + cost[k];                        // update minimum cost seen so far                        if(currCost < minCost)                        {                            minCost = currCost;                        }                    }                }            }        }        // return minimum cost of valid triplets        returnminCost;    }    publicstaticvoidMain(string[] args)    {        int[] arr = { 2, 4, 5, 4, 10 };        int[] cost = { 40, 30, 20, 10, 40 };        intn = arr.Length;        Console.WriteLine(MinCostTriplet(arr, cost, n));    }}//This code is contributed by aeroabrar_31 | 
Javascript
| <script>functionminCostTriplet(arr, cost, n) {    let minCost = Number.MAX_VALUE;    // Iterate over all possible triplets of elements    for(let i = 0; i < n - 2; i++) {        for(let j = i + 1; j < n - 1; j++) {            for(let k = j + 1; k < n; k++) {                // Check if triplet forms an increasing sequence                if(arr[i] < arr[j] && arr[j] < arr[k]) {                    const currCost = cost[i] + cost[j] + cost[k];                    // Update minimum cost seen so far                    if(currCost < minCost) {                        minCost = currCost;                    }                }            }        }    }    // Return minimum cost of valid triplets    returnminCost;}functionmain() {    const arr = [2, 4, 5, 4, 10];    const cost = [40, 30, 20, 10, 40];    const n = arr.length;    console.log(minCostTriplet(arr, cost, n));}main();//This code is contributed by aeroabrar_31</script> | 
90
Time Complexity: O(n^3), where n is the size of the given arrays.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Efficient approach: An efficient approach is to fix the middle element and search for the smaller element with minimum cost on its left and the larger element with minimum cost on its right in the given array. If a valid triplet is found then update the minimum cost far. The time complexity of this approach will be O(n2).
Below is the implementation of the above approach:
C++
| // C++ implementation of the approach#include <bits/stdc++.h>usingnamespacestd;// Function to return the minimum required costintminCost(intarr[], intcost[], intn){    // To store the cost of choosing three elements    intcostThree = INT_MAX;    // Fix the middle element    for(intj = 0; j < n; j++) {        // Initialize cost of the first        // and the third element        intcostI = INT_MAX, costK = INT_MAX;        // Search for the first element        // in the left subarray        for(inti = 0; i < j; i++) {            // If smaller element is found            // then update the cost            if(arr[i] < arr[j])                costI = min(costI, cost[i]);        }        // Search for the third element        // in the right subarray        for(intk = j + 1; k < n; k++) {            // If greater element is found            // then update the cost            if(arr[k] > arr[j])                costK = min(costK, cost[k]);        }        // If a valid triplet was found then        // update the minimum cost so far        if(costI != INT_MAX && costK != INT_MAX) {            costThree = min(costThree, cost[j]                                           + costI                                           + costK);        }    }    // No such triplet found    if(costThree == INT_MAX)        return-1;    returncostThree;}// Driver codeintmain(){    intarr[] = { 2, 4, 5, 4, 10 };    intcost[] = { 40, 30, 20, 10, 40 };    intn = sizeof(arr) / sizeof(arr[0]);    cout << minCost(arr, cost, n);    return0;} | 
Java
| // Java implementation of the approach classGFG {    // Function to return the minimum required cost staticintminCost(intarr[], intcost[], intn) {     // To store the cost of choosing three elements     intcostThree = Integer.MAX_VALUE;     // Fix the middle element     for(intj = 0; j < n; j++)    {         // Initialize cost of the first         // and the third element         intcostI = Integer.MAX_VALUE;         intcostK = Integer.MAX_VALUE;         // Search for the first element         // in the left subarray         for(inti = 0; i < j; i++)         {             // If smaller element is found             // then update the cost             if(arr[i] < arr[j])                 costI = Math.min(costI, cost[i]);         }         // Search for the third element         // in the right subarray         for(intk = j + 1; k < n; k++)         {             // If greater element is found             // then update the cost             if(arr[k] > arr[j])                 costK = Math.min(costK, cost[k]);         }         // If a valid triplet was found then         // update the minimum cost so far         if(costI != Integer.MAX_VALUE &&             costK != Integer.MAX_VALUE)        {             costThree = Math.min(costThree, cost[j] +                                     costI + costK);         }     }     // No such triplet found     if(costThree == Integer.MAX_VALUE)         return-1;             returncostThree; } // Driver code publicstaticvoidmain (String[] args) {     intarr[] = { 2, 4, 5, 4, 10};     intcost[] = { 40, 30, 20, 10, 40};     intn = arr.length;     System.out.println(minCost(arr, cost, n)); } }// This code is contributed by AnkitRai01 | 
Python3
| # Python3 implementation of the approach# Function to return the minimum required costdefminCost(arr, cost, n):    # To store the cost of choosing three elements    costThree =10**9    # Fix the middle element    forj inrange(n):        # Initialize cost of the first        # and the third element        costI =10**9        costK =10**9        # Search for the first element        # in the left subarray        fori inrange(j):            # If smaller element is found            # then update the cost            if(arr[i] < arr[j]):                costI =min(costI, cost[i])        # Search for the third element        # in the right subarray        fork inrange(j +1, n):            # If greater element is found            # then update the cost            if(arr[k] > arr[j]):                costK =min(costK, cost[k])        # If a valid triplet was found then        # update the minimum cost so far        if(costI !=10**9andcostK !=10**9):            costThree =min(costThree, cost[j] +                               costI +costK)    # No such triplet found    if(costThree ==10**9):        return-1    returncostThree# Driver codearr =[2, 4, 5, 4, 10]cost =[40, 30, 20, 10, 40]n =len(arr)print(minCost(arr, cost, n))# This code is contributed by Mohit Kumar | 
C#
| // C# implementation of the approach usingSystem;classGFG{        // Function to return the // minimum required cost staticintminCost(int[]arr,                    int[]cost, intn) {     // To store the cost of     // choosing three elements     intcostThree = int.MaxValue;     // Fix the middle element     for(intj = 0; j < n; j++)    {         // Initialize cost of the first         // and the third element         intcostI = int.MaxValue;         intcostK = int.MaxValue;         // Search for the first element         // in the left subarray         for(inti = 0; i < j; i++)         {             // If smaller element is found             // then update the cost             if(arr[i] < arr[j])                 costI = Math.Min(costI, cost[i]);         }         // Search for the third element         // in the right subarray         for(intk = j + 1; k < n; k++)         {             // If greater element is found             // then update the cost             if(arr[k] > arr[j])                 costK = Math.Min(costK, cost[k]);         }         // If a valid triplet was found then         // update the minimum cost so far         if(costI != int.MaxValue &&             costK != int.MaxValue)        {             costThree = Math.Min(costThree, cost[j] +                                     costI + costK);         }     }     // No such triplet found     if(costThree == int.MaxValue)         return-1;             returncostThree; } // Driver code staticpublicvoidMain (){    int[]arr = { 2, 4, 5, 4, 10 };     int[]cost = { 40, 30, 20, 10, 40 };     intn = arr.Length;     Console.Write(minCost(arr, cost, n)); } }// This code is contributed by Sachin.. | 
Javascript
| <script>// JavaScript implementation of the approach // Function to return the minimum required cost functionminCost(arr,cost,n){    // To store the cost of choosing three elements     let costThree = Number.MAX_VALUE;       // Fix the middle element     for(let j = 0; j < n; j++)    {           // Initialize cost of the first         // and the third element         let costI = Number.MAX_VALUE;         let costK = Number.MAX_VALUE;           // Search for the first element         // in the left subarray         for(let i = 0; i < j; i++)         {               // If smaller element is found             // then update the cost             if(arr[i] < arr[j])                 costI = Math.min(costI, cost[i]);         }           // Search for the third element         // in the right subarray         for(let k = j + 1; k < n; k++)         {               // If greater element is found             // then update the cost             if(arr[k] > arr[j])                 costK = Math.min(costK, cost[k]);         }           // If a valid triplet was found then         // update the minimum cost so far         if(costI != Number.MAX_VALUE &&             costK != Number.MAX_VALUE)        {             costThree = Math.min(costThree, cost[j] +                                     costI + costK);         }     }       // No such triplet found     if(costThree == Number.MAX_VALUE)         return-1;               returncostThree; }// Driver code let arr=[2, 4, 5, 4, 10];let cost=[40, 30, 20, 10, 40 ];let n = arr.length; document.write(minCost(arr, cost, n));// This code is contributed by unknown2108</script> | 
90
Time Complexity: O(n2), where n is the size of the given arrays.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!


 
                                    







