Minimum Sum of a pair at least K distance apart from an Array | C ++ Program to implement the above approach ; Function to find the minimum sum of two elements that are atleast K distance apart ; Length of the array ; Find the suffix array ; Iterate in the array ; Update minimum sum ; Print the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMinSum ( int A [ ] , int K , int len ) { int n = len ; int suffix_min [ n ] = { 0 } ; suffix_min [ n - 1 ] = A [ n - 1 ] ; for ( int i = n - 2 ; i >= 0 ; i -- ) suffix_min [ i ] = min ( suffix_min [ i + 1 ] , A [ i ] ) ; int min_sum = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { if ( i + K < n ) min_sum = min ( min_sum , A [ i ] + suffix_min [ i + K ] ) ; } cout << min_sum ; } 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 ; }