Open In App

Find minimum pair sum by selecting element from 2nd array at index larger than 1st array

Last Updated : 28 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given two arrays A[] and B[] of size N each, the task is to minimize A[i] + B[j] such that j ≥ i.

Examples:

Input: A[] = {34, 12, 45, 10, 86, 39, 77},  
           B[] = {5, 42, 29, 63, 30, 33, 20}
Output: 30
Explanation: For minimizing the sum, take i = 3 and j = 6.

Input: A[] = {34, 17, 45, 10, 19},  
           B[] = {2, 13, 7, 11, 16}
Output: 21
Explanation: For minimizing the sum, take both i and j = 3.

 

Naive Approach: The naive approach to solve this problem is to use 2 for loops, one for iterating over A[] and another for iterating over B[]. Just check and compare for all the possibilities to minimize the sum. 

Below is the implementation of the above naive approach.

C++




// C++ program for above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to minimize the sum
int minimumCost(int A[], int B[], int N)
{
    int minimuPrice = INT_MAX;
 
    // Checking and comparing for
    // all the possibilities
    for (int i = 0; i < N; i++) {
        for (int j = i; j < N; j++) {
            int currentPrice = A[i] + B[j];
            minimuPrice = min(minimuPrice,
                              currentPrice);
        }
    }
 
    // Return the minimum price found
    return minimuPrice;
}
 
// Driver Code
int main()
{
    int A[] = { 34, 12, 45, 10, 86, 39, 77 };
    int B[] = { 5, 42, 29, 63, 30, 33, 20 };
    int N = sizeof(A) / sizeof(A[0]);
 
    // Function Call
    cout << minimumCost(A, B, N);
    return 0;
}


Java




// Java program for above approach
import java.io.*;
 
class GFG {
 
    // Function to minimize the sum
    public static int minimumCost(int[] A,
                                  int[] B,
                                  int N)
    {
        int minimuPrice = Integer.MAX_VALUE;
 
        // Checking and comparing
        // for all the possibilities
        for (int i = 0; i < N; i++) {
            for (int j = i; j < N; j++) {
                int currentPrice
                    = A[i] + B[j];
                minimuPrice
                    = Math.min(minimuPrice,
                               currentPrice);
            }
        }
        return minimuPrice;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[] A = { 34, 12, 45, 10, 86, 39, 77 };
        int[] B = { 5, 42, 29, 63, 30, 33, 20 };
        int N = A.length;
        System.out.println(minimumCost(A, B, N));
    }
}


Python




# Python program for above approach
# import the module
import sys
 
# Function to minimize the sum
def minimumCost(A, B, N):
 
    minimuPrice = sys.maxint
 
    # Checking and comparing for
    # all the possibilities
    for i in range(N):
        for j in range(i, N):
              currentPrice = A[i] + B[j]
              minimuPrice = min(minimuPrice,
                              currentPrice)
    
    # Return the minimum price found
    return minimuPrice;
 
# Driver Code
if __name__ == "__main__":
   
    A = [ 34, 12, 45, 10, 86, 39, 77 ]
    B = [ 5, 42, 29, 63, 30, 33, 20 ]
 
    N = len(A)
 
    # Function Call
    print(minimumCost(A, B, N))
     
    # This code is contributed by hrithikgarg03188.


C#




// C# program for above approach
using System;
class GFG
{
 
  // Function to minimize the sum
  static int minimumCost(int[] A, int[] B, int N)
  {
    int minimuPrice = Int32.MaxValue;
 
    // Checking and comparing for
    // all the possibilities
    for (int i = 0; i < N; i++) {
      for (int j = i; j < N; j++) {
        int currentPrice = A[i] + B[j];
        minimuPrice
          = Math.Min(minimuPrice, currentPrice);
      }
    }
 
    // Return the minimum price found
    return minimuPrice;
  }
 
  // Driver Code
  public static int Main()
  {
    int[] A = { 34, 12, 45, 10, 86, 39, 77 };
    int[] B = { 5, 42, 29, 63, 30, 33, 20 };
    int N = A.Length;
 
    // Function Call
    Console.Write(minimumCost(A, B, N));
    return 0;
  }
}
 
// This code is contributed by Taranpreet


Javascript




<script>
    // JavaScript program for above approach
    const INT_MAX = 2147483647;
     
    // Function to minimize the sum
    const minimumCost = (A, B, N) => {
        let minimuPrice = INT_MAX;
 
        // Checking and comparing for
        // all the possibilities
        for (let i = 0; i < N; i++) {
            for (let j = i; j < N; j++) {
                let currentPrice = A[i] + B[j];
                minimuPrice = Math.min(minimuPrice,
                    currentPrice);
            }
        }
 
        // Return the minimum price found
        return minimuPrice;
    }
 
    // Driver Code
 
    let A = [34, 12, 45, 10, 86, 39, 77];
    let B = [5, 42, 29, 63, 30, 33, 20];
    let N = A.length;
 
    // Function Call
    document.write(minimumCost(A, B, N));
 
    // This code is contributed by rakeshsahni
 
</script>


 
 

Output

30

 

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

 

Efficient Approach: An efficient way to solve this problem is to create an array that contains the minimum value till ith index from the rear end of B[]. Then traverse through A[] and for each index the minimum sum will be the sum of minimum from starting of A[] and minimum from back of B[] till that index. Follow the steps below to solve the given problem.

 

  • Create an array for storing the minimum value from the rear end of B[] for each index.
  • Since there is only one possible value on the last index, assign the last index value of array B[] to the last index of the new array.
  • Now, traverse B[] from the rear side and compare the current index (say i) value in B[] with the index (i+1) in the new array and store the minimum value of these two in the ith index of the newly created array.
  • Now, iterate over elements of X and look at that index in the new array. Since that index at new array is the smallest possible value present in B[] for i and above.

 

Below is the implementation of the above efficient approach.

 

C++




// C++ program for above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate minimum sum
int minimumCost(int A[], int B[], int N)
{
    // For storing the minimum value
    // from rear end of B[]
    int cheapestPossible[N];
 
    // Only one possible value on last index
    cheapestPossible[N - 1] = B[N - 1];
 
    for (int i = (N - 2); i >= 0; i--) {
 
        // The lowest possible sum at
        // index i and above
        cheapestPossible[i]
            = min(cheapestPossible[i + 1],
                  B[i]);
    }
 
    // For storing minimum sum
    int minimumPrice = INT_MAX;
 
    // Adding the current value of A[] and
    // minimum value of B[] after i and
    // comparing it with the last minimum sum
    for (int i = 0; i < N; i++) {
        minimumPrice
            = min(minimumPrice,
                  A[i] + cheapestPossible[i]);
    }
    return minimumPrice;
}
 
// Driver Code
int main()
{
    int A[] = { 34, 12, 45, 10, 86, 39, 77 };
    int B[] = { 5, 42, 29, 63, 30, 33, 20 };
    int N = sizeof(A) / sizeof(A[0]);
 
    // Function Call
    cout << minimumCost(A, B, N);
    return 0;
}


Java




// Java program for above approach
import java.io.*;
 
class GFG {
 
    // Function to calculate minimum sum
    public static int minimumCost(int[] A,
                                  int[] B,
                                  int N)
    {
        // For storing the minimum value
        // from rear end of B[]
        int[] cheapestPossible = new int[N];
 
        // Only one possible value
        // on last index
        cheapestPossible[N - 1]
            = B[N - 1];
 
        for (int i = (N - 2); i >= 0; i--) {
 
            // The lowest possible sum at
            // index i and above
            cheapestPossible[i]
                = Math.min(cheapestPossible[i + 1],
                           B[i]);
        }
 
        // For storing minimum sum
        int minimumPrice = Integer.MAX_VALUE;
 
        // Adding the current value of A[]
        // and minimum value of B[] after i
        // and comparing it with
        // the last minimum sum obtained
        for (int i = 0; i < N; i++) {
            minimumPrice = Math.min(
                minimumPrice, A[i]
                                  + cheapestPossible[i]);
        }
        return minimumPrice;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int[] A = { 34, 12, 45, 10, 86, 39, 77 };
        int[] B = { 5, 42, 29, 63, 30, 33, 20 };
        int N = A.length;
        System.out.println(minimumCost(A, B, N));
    }
}


Python3




# Python 3 program for above approach
import sys
 
# Function to calculate minimum sum
def minimumCost(A, B, N):
 
    # For storing the minimum value
    # from rear end of B[]
    cheapestPossible = [0]*N
 
    # Only one possible value on last index
    cheapestPossible[N - 1] = B[N - 1]
 
    for i in range(N - 2 ,- 1, -1):
 
        # The lowest possible sum at
        # index i and above
        cheapestPossible[i] = min(cheapestPossible[i + 1],
                                  B[i])
 
    # For storing minimum sum
    minimumPrice = sys.maxsize
 
    # Adding the current value of A[] and
    # minimum value of B[] after i and
    # comparing it with the last minimum sum
    for i in range(N):
        minimumPrice = min(minimumPrice,
                           A[i] + cheapestPossible[i])
 
    return minimumPrice
 
# Driver Code
if __name__ == "__main__":
 
    A = [34, 12, 45, 10, 86, 39, 77]
    B = [5, 42, 29, 63, 30, 33, 20]
    N = len(A)
 
    # Function Call
    print(minimumCost(A, B, N))
 
    # This code is contributed by ukasp.


C#




// C# program for above approach
using System;
using System.Collections.Generic;
public class GFG {
 
  // Function to calculate minimum sum
  public static int minimumCost(int[] A,
                                int[] B,
                                int N)
  {
     
    // For storing the minimum value
    // from rear end of []B
    int[] cheapestPossible = new int[N];
 
    // Only one possible value
    // on last index
    cheapestPossible[N - 1]
      = B[N - 1];
 
    for (int i = (N - 2); i >= 0; i--) {
 
      // The lowest possible sum at
      // index i and above
      cheapestPossible[i]
        = Math.Min(cheapestPossible[i + 1],
                   B[i]);
    }
 
    // For storing minimum sum
    int minimumPrice = int.MaxValue;
 
    // Adding the current value of []A
    // and minimum value of []B after i
    // and comparing it with
    // the last minimum sum obtained
    for (int i = 0; i < N; i++) {
      minimumPrice = Math.Min(
        minimumPrice, A[i]
        + cheapestPossible[i]);
    }
    return minimumPrice;
  }
 
  // Driver code
  public static void Main(String[] args)
  {
    int[] A = { 34, 12, 45, 10, 86, 39, 77 };
    int[] B = { 5, 42, 29, 63, 30, 33, 20 };
    int N = A.Length;
    Console.WriteLine(minimumCost(A, B, N));
  }
}
 
// This code is contributed by shikhasingrajput


Javascript




<script>
// javascript program for above approach
 
   // Function to calculate minimum sum
    function minimumCost(A, B, N)
    {
     
        // For storing the minimum value
        // from rear end of B
        var cheapestPossible = Array.from({length: N}, (_, i) => 0);
 
        // Only one possible value
        // on last index
        cheapestPossible[N - 1]
            = B[N - 1];
 
        for (var i = (N - 2); i >= 0; i--) {
 
            // The lowest possible sum at
            // index i and above
            cheapestPossible[i]
                = Math.min(cheapestPossible[i + 1],
                           B[i]);
        }
 
        // For storing minimum sum
        var minimumPrice = Number.MAX_VALUE;
 
        // Adding the current value of A
        // and minimum value of B after i
        // and comparing it with
        // the last minimum sum obtained
        for (var i = 0; i < N; i++) {
            minimumPrice = Math.min(
                minimumPrice, A[i]
                                  + cheapestPossible[i]);
        }
        return minimumPrice;
    }
 
    // Driver code
var A = [ 34, 12, 45, 10, 86, 39, 77 ];
var B = [ 5, 42, 29, 63, 30, 33, 20 ];
var N = A.length;
document.write(minimumCost(A, B, N));
 
// This code is contributed by shikhasingrajput
</script>


 
 

Output

30

 

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

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads