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 ; Iterate over the array ; Initialize the min value ; Iterate from i + k to N ; Find the minimum ; Update the minimum sum ; Print the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMinSum ( int A [ ] , int K , int n ) { int minimum_sum = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { int mini = INT_MAX ; for ( int j = i + K ; j < n ; j ++ ) mini = min ( mini , A [ j ] ) ; if ( mini == INT_MAX ) continue ; minimum_sum = min ( minimum_sum , A [ i ] + mini ) ; } cout << ( minimum_sum ) ; } 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 ; }