Minimum Sum of a pair at least K distance apart from an Array | 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 ; Prlet the answer ; Driver Code
function findMinSum ( A , K ) { let n = A . length ; let suffix_min = Array . from ( { length : n } , ( _ , i ) => 0 ) ; suffix_min [ n - 1 ] = A [ n - 1 ] ; for ( let i = n - 2 ; i >= 0 ; i -- ) suffix_min [ i ] = Math . min ( suffix_min [ i + 1 ] , A [ i ] ) ; let min_sum = Number . MAX_VALUE ; for ( let i = 0 ; i < n ; i ++ ) { if ( i + K < n ) min_sum = Math . min ( min_sum , A [ i ] + suffix_min [ i + K ] ) ; } document . write ( min_sum ) ; } let A = [ 1 , 2 , 3 , 4 , 5 , 6 ] ; let K = 2 ; findMinSum ( A , K ) ;