Minimum possible sum of prices of a Triplet from the given Array

Given an array num[] of N integers where each element is associated with a price given by another array price[], the task is to minimize the sum of price by taking a triplet such that num[i] < num[j] < num[k]. If there is no such triplet then print -1.

Examples: 

Input: num[]={2, 4, 6, 7, 8}, price[]={10, 20, 100, 20, 40} 
Output: 50 
Explanation: 
Selecting the triplet {2, 4, 7} because (2 < 4 < 7), and the price is 10 + 20 + 20 = 50 which is the minimum possible.

Input: num[]={100, 101, 100}, price[]={2, 4, 5} 
Output: -1 
Explanation: 
No possible triplet exists. 

Naive Approach: 
The simplest approach is to generate all possible triplets (i, j, k) such that i < j < k and num[i] < num[j] < num[k] then find the sum of prices[i], prices[j], and prices[k]. Print the minimum sum of all such triplets.



Time Complexity: O(N3)
Auxiliary Space: O(1)

Efficient Approach: The idea is to use auxiliary array dp[] to store the minimum sum of prices of all such triplets and print the minimum of all the prices stored in it. Below are the steps:

  1. Initialize the dp[] array to INT_MAX.
  2. Initialize the current minimum sum(say current_sum) to INT_MAX.
  3. Generate all possible pairs (i, j) such that j > i. If nums[j] > num[i] then update dp[j] = min(dp[j], price[i] + price[j]) as this is one of the possible pairs.
  4. In each pair (i, j) in the above steps update the minimum sum of triplets to min(current_sum, dp[i] + price[j]). This step will ensure that the possible triplets (i, j, k) is formed as dp[i] will store the sum of the price at index i and j, and j is the value of k.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to implement
// the above approach
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
  
// Function to minimize the sum of
// price by taking a triplet
long minSum(int n, int num[], int price[])
{
      
    // Initialize a dp[] array
    long dp[n];
  
    for(int i = 0; i < n; i++)
        dp[i] = INT_MAX;
  
    // Stores the final result
    long ans = INT_MAX;
  
    // Iterate for all values till N
    for(int i = 0; i < n; i++)
    {
        for(int j = i + 1; j < n; j++)
        {
              
            // Check if num[j] > num[i]
            if (num[j] > num[i]) 
            {
                  
                // Update dp[j] if it is
                // greater than stored value
                dp[j] = (long)min((long)dp[j],
                                  (long)price[i] +
                                  (long)price[j]);
  
                // Update the minimum
                // sum as ans
                ans = min(ans, (long)dp[i] +
                               (long)price[j]);
            }
        }
    }
      
    // If there is no minimum sum exist
    // then print -1 else print the ans
    return ans != INT_MAX ? ans : -1;
}
  
// Driver Code
int main()
{
    int num[] = { 2, 4, 6, 7, 8 };
    int price[] = { 10, 20, 100, 20, 40 };
      
    int n = sizeof(price) / sizeof(price[0]);
      
    cout << (minSum(n, num, price));
}
  
// This code is contributed by chitranayal

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to implement
// the above approach
import java.util.*;
import java.io.*;
  
public class Main {
  
    // Function to minimize the sum of
    // price by taking a triplet
    public static long minSum(int n, int num[],
                              int price[])
    {
  
        // Initialize a dp[] array
        long dp[] = new long[n];
  
        Arrays.fill(dp, Integer.MAX_VALUE);
  
        // Stores the final result
        long ans = Integer.MAX_VALUE;
  
        // Iterate for all values till N
        for (int i = 0; i < n; i++) {
  
            for (int j = i + 1; j < n; j++) {
  
                // Check if num[j] > num[i]
                if (num[j] > num[i]) {
  
                    // Update dp[j] if it is
                    // greater than stored value
                    dp[j] = (long)Math.min(
                        (long)dp[j],
                        (long)price[i]
                            + (long)price[j]);
  
                    // Update the minimum
                    // sum as ans
                    ans = Math.min(
                        ans, (long)dp[i]
                                 + (long)price[j]);
                    
                }
            }
        }
        
  
        // If there is no minimum sum exist
        // then print -1 else print the ans
        return ans != Integer.MAX_VALUE ? ans : -1;
    }
  
    // Driver Code
    public static void
        main(String[] args)
    {
  
        int num[] = { 2, 4, 6, 7, 8 };
        int price[] = { 10, 20, 100, 20, 40 };
  
        int n = price.length;
  
        System.out.println(minSum(n, num, price));
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above approach
import sys;
  
# Function to minimize the sum of
# price by taking a triplet
def minSum(n, num, price):
      
    # Initialize a dp[] list
    dp = [0 for i in range(n)]
    for i in range(n):
        dp[i] = sys.maxsize
  
    # Stores the final result
    ans = sys.maxsize
  
    # Iterate for all values till N
    for i in range(n):
        for j in range(i + 1, n):
              
            # Check if num[j] > num[i]
            if (num[j] > num[i]):
                  
                # Update dp[j] if it is
                # greater than stored value
                dp[j] = min(dp[j], price[i] + 
                                   price[j])
  
                # Update the minimum
                # sum as ans
                ans = min(ans, dp[i] + price[j])
                  
    # If there is no minimum sum exist
    # then print -1 else print the ans
    if ans is not sys.maxsize:
        return ans
    else:
        return -1
  
# Driver code
if __name__=='__main__':
      
    num = [ 2, 4, 6, 7, 8 ]
    price = [ 10, 20, 100, 20, 40 ]
      
    n = len(price)
      
    print(minSum(n, num, price))
  
# This code is contributed by rutvik_56

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above approach
using System;
  
class GFG{
  
// Function to minimize the sum of
// price by taking a triplet
public static long minSum(int n, int []num,
                          int []price)
{
      
    // Initialize a []dp array
    long []dp = new long[n];
    for(int i = 0; i < n; i++)
        dp[i] = int.MaxValue;
  
    // Stores the readonly result
    long ans = int.MaxValue;
  
    // Iterate for all values till N
    for(int i = 0; i < n; i++)
    {
        for(int j = i + 1; j < n; j++)
        {
  
            // Check if num[j] > num[i]
            if (num[j] > num[i]) 
            {
  
                // Update dp[j] if it is
                // greater than stored value
                dp[j] = (long)Math.Min((long)dp[j],
                                       (long)price[i] +
                                       (long)price[j]);
  
                // Update the minimum
                // sum as ans
                ans = Math.Min(ans, (long)dp[i] +
                                    (long)price[j]);
            }
        }
    }
      
    // If there is no minimum sum exist
    // then print -1 else print the ans
    return ans != int.MaxValue ? ans : -1;
}
  
// Driver Code
public static void Main(String[] args)
{
    int []num = { 2, 4, 6, 7, 8 };
    int []price = { 10, 20, 100, 20, 40 };
  
    int n = price.Length;
  
    Console.WriteLine(minSum(n, num, price));
}
}
  
// This code is contributed by 29AjayKumar

chevron_right


Output: 

50

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.