s | To sort the array and return the answer ; sort the array ; Fill all stated with - 1 when only one element ; As dp [ 0 ] = 0 ( base case ) so min no of elements to be removed are n - 1 elements ; Iterate from 1 to n - 1 ; Driver code
def removals ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE dp = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT dp [ i ] = - 1 NEW_LINE DEDENT ans = n - 1 NEW_LINE dp [ 0 ] = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT dp [ i ] = i NEW_LINE j = dp [ i - 1 ] NEW_LINE while ( j != i and arr [ i ] - arr [ j ] > k ) : NEW_LINE j += 1 NEW_LINE dp [ i ] = min ( dp [ i ] , j ) NEW_LINE ans = min ( ans , ( n - ( i - j + 1 ) ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT a = [ 1 , 3 , 4 , 9 , 10 , 11 , 12 , 17 , 20 ] NEW_LINE n = len ( a ) NEW_LINE k = 4 NEW_LINE print ( removals ( a , n , k ) ) NEW_LINE