Related Articles

Related Articles

Minimum Sum of a pair at least K distance apart from an Array
  • Last Updated : 25 Aug, 2020

Given an array of integers A[] of size N, the task is to find the minimum sum that can be obtained by any pair of array elements which are at least K indices apart from each other.

Examples:

Input: A[] = {1, 2, 3, 4, 5, 6}, K = 2 
Output:
Explanation: 
The minimum sum that can be obtained is by adding 1 and 3 that are at a distance of 2.

Input: A[] = {4, 2, 5, 4, 3, 2, 5}, K = 3 
Output:
Explanation: 
The minimum sum that can be obtained is by adding 2 and 2 that are at a distance of 4.

Naive Approach: 
The simplest approach is to solve the problem is to iterate over the indices [i + K, N – 1] for every ith index and find the minimum element, say min. Check if min + A[i] is less than the minimum sum obtained so far and update minimum_sum accordingly. Finally, print the minimum_sum.



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<bits/stdc++.h>
using namespace std;
  
// Function to find the minimum
// sum of two elements that
// are atleast K distance apart
void findMinSum(int A[], int K, int n)
{
    int minimum_sum = INT_MAX;
  
    // Iterate over the array
    for(int i = 0; i < n; i++)
    {
          
        // Initialize the min value
        int mini = INT_MAX;
  
        // Iterate from i + k to N
        for(int j = i + K; j < n; j++)
  
            // Find the minimum
            mini = min(mini, A[j]);
  
        if (mini == INT_MAX)
            continue;
  
        // Update the minimum sum
        minimum_sum = min(minimum_sum,
                          A[i] + mini);
    }
  
    // Print the answer
    cout << (minimum_sum);
}
  
// Driver Code
int main()
{
    int A[] = { 4, 2, 5, 4, 3, 2, 5 };
    int K = 3;
    int n = sizeof(A) / sizeof(A[0]);
  
    findMinSum(A, K, n);
    return 0;
}
  
// 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.*;
class GFG {
  
    // Function to find the minimum
    // sum of two elements that
    // are atleast K distance apart
    public static void
    findMinSum(int A[], int K)
    {
        // Length of the array
        int n = A.length;
  
        int minimum_sum
            = Integer.MAX_VALUE;
  
        // Iterate over the array
        for (int i = 0; i < n; i++) {
  
            // Initialize the min value
            int min = Integer.MAX_VALUE;
  
            // Iterate from i + k to N
            for (int j = i + K; j < n; j++)
  
                // Find the minimum
                min = Math.min(min, A[j]);
  
            if (min == Integer.MAX_VALUE)
                continue;
  
            // Update the minimum sum
            minimum_sum = Math.min(minimum_sum,
                                   A[i] + min);
        }
  
        // Print the answer
        System.out.println(minimum_sum);
    }
  
    // Driver Code
    public static void
        main(String[] args)
    {
  
        int A[] = { 4, 2, 5, 4, 3, 2, 5 };
        int K = 3;
  
        findMinSum(A, K);
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 Program to implement
# the above approach
import sys
  
# Function to find the minimum
# sum of two elements that
# are atleast K distance apart
def findMinSum(A, K):
    
    # Length of the array
    n = len(A);
  
    minimum_sum = sys.maxsize;
  
    # Iterate over the array
    for i in range(n):
  
        # Initialize the min value
        minmum = sys.maxsize;
  
        # Iterate from i + k to N
        for j in range(i + K, n, 1):
  
            # Find the minimum
            minmum = min(minmum, A[j]);
  
        if (minmum == sys.maxsize):
            continue;
  
        # Update the minimum sum
        minimum_sum = min(minimum_sum, A[i] + minmum);
  
    # Prthe answer
    print(minimum_sum);
  
# Driver Code
if __name__ == '__main__':
    A = [4, 2, 5, 4, 3, 2, 5];
    K = 3;
  
    findMinSum(A, K);
  
# This code is contributed by sapnasingh4991

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 find the minimum
  // sum of two elements that
  // are atleast K distance apart
  public static void findMinSum(int []A,
                                int K)
  {
    // Length of the array
    int n = A.Length;
  
    int minimum_sum = int.MaxValue;
  
    // Iterate over the array
    for (int i = 0; i < n; i++)
    {
  
      // Initialize the min value
      int min = int.MaxValue;
  
      // Iterate from i + k to N
      for (int j = i + K; j < n; j++)
  
        // Find the minimum
        min = Math.Min(min, A[j]);
  
      if (min == int.MaxValue)
        continue;
  
      // Update the minimum sum
      minimum_sum = Math.Min(minimum_sum,
                             A[i] + min);
    }
  
    // Print the answer
    Console.WriteLine(minimum_sum);
  }
  
  // Driver Code
  public static void Main(String[] args)
  {
    int []A = { 4, 2, 5, 4, 3, 2, 5 };
    int K = 3;
  
    findMinSum(A, K);
  }
}
  
// This code is contributed by Rohit_ranjan

chevron_right


Output: 

4

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

Efficient Approach: 
The above approach can be optimized using a Suffix Array. Follow the steps below:

  • Initialize a suffix array(say suffix[]), where suffix[i] stores the minimum of all the elements from index N-1 to i.
  • For any ith index, the minimum element which is K distance apart is stored at index i + K in the suffix array.
  • For i ranging from 0 to N – 1, check if A[i] + suffix[i + k] < minimum_sum or not and update minimum_sum accordingly.
  • Finally, print minimum_sum as the required answer.

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 <bits/stdc++.h>
using namespace std;
  
// Function to find the minimum
// sum of two elements that
// are atleast K distance apart
void findMinSum(int A[], int K, int len)
{
  
  // Length of the array
  int n = len;
  int suffix_min[n] = {0};
  
  suffix_min[n - 1] = A[n - 1];
  
  // Find the suffix array
  for (int i = n - 2; i >= 0; i--)
    suffix_min[i] = min(suffix_min[i + 1], A[i]);
  
  int min_sum = INT_MAX;
  
  // Iterate in the array
  for (int i = 0; i < n; i++) 
  {
    if (i + K < n)
  
      // Update minimum sum
      min_sum = min(min_sum, A[i] + 
                    suffix_min[i + K]);
  }
  
  // Print the answer
  cout << min_sum;
}
  
  
// Driver Code
int main()
{
    int A[] = { 1, 2, 3, 4, 5, 6 };
    int K = 2;
    int n = sizeof(A) / sizeof(A[0]);
    findMinSum(A, K, n);
    return 0;
}
  
// This code is contributed by Rohit_ranjan

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to implement
// the above approach
  
import java.util.*;
class GFG {
  
    // Function to find the minimum
    // sum of two elements that
    // are atleast K distance apart
    public static void
    findMinSum(int A[], int K)
    {
  
        // Length of the array
        int n = A.length;
        int suffix_min[] = new int[n];
  
        suffix_min[n - 1] = A[n - 1];
  
        // Find the suffix array
        for (int i = n - 2; i >= 0; i--)
            suffix_min[i]
                = Math.min(suffix_min[i + 1],
                           A[i]);
  
        int min_sum = Integer.MAX_VALUE;
  
        // Iterate in the array
        for (int i = 0; i < n; i++) {
  
            if (i + K < n)
  
                // Update minimum sum
                min_sum = Math.min(
                    min_sum, A[i]
                                 + suffix_min[i + K]);
        }
  
        // Print the answer
        System.out.println(min_sum);
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        int A[] = { 1, 2, 3, 4, 5, 6 };
        int K = 2;
  
        findMinSum(A, K);
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above approach
import sys
  
# Function to find the minimum
# sum of two elements that
# are atleast K distance apart
def findMinSum(A, K):
      
    # Length of the array
    n = len(A);
      
    suffix_min = [0] * n;
    suffix_min[n - 1] = A[n - 1];
  
    # Find the suffix array
    for i in range(n - 2, -1, -1):
        suffix_min[i] = min(suffix_min[i + 1], A[i]);
  
    min_sum = sys.maxsize;
  
    # Iterate in the array
    for i in range(n):
        if (i + K < n):
  
            # Update minimum sum
            min_sum = min(min_sum, A[i] + 
                          suffix_min[i + K]);
  
    # Print the answer
    print(min_sum);
  
# Driver Code
if __name__ == '__main__':
      
    A = [ 1, 2, 3, 4, 5, 6 ];
    K = 2;
  
    findMinSum(A, K);
  
# This code is contributed by Amit Katiyar

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 find the minimum
// sum of two elements that
// are atleast K distance apart
public static void findMinSum(int []A, int K)
{
      
    // Length of the array
    int n = A.Length;
    int []suffix_min = new int[n];
  
    suffix_min[n - 1] = A[n - 1];
  
    // Find the suffix array
    for(int i = n - 2; i >= 0; i--)
        suffix_min[i] = Math.Min(suffix_min[i + 1],
                                          A[i]);
  
    int min_sum = int.MaxValue;
  
    // Iterate in the array
    for(int i = 0; i < n; i++) 
    {
        if (i + K < n)
  
            // Update minimum sum
            min_sum = Math.Min(min_sum, A[i] + 
                               suffix_min[i + K]);
    }
  
    // Print the answer
    Console.WriteLine(min_sum);
}
  
// Driver Code
public static void Main(String[] args)
{
    int []A = { 1, 2, 3, 4, 5, 6 };
    int K = 2;
  
    findMinSum(A, K);
}
}
  
// This code is contributed by 29AjayKumar 

chevron_right


Output: 

4

Time Complexity: O(N) 
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
Recommended Articles
Page :