Iterate from 1 to n - 1
for ( int i = 1 ; i < n ; i ++ ) { dp [ i ] = i ; int j = dp [ i - 1 ] ; while ( j != i && arr [ i ] - arr [ j ] > k ) { j ++ ; } dp [ i ] = min ( dp [ i ] , j ) ; ans = min ( ans , ( n - ( i - j + 1 ) ) ) ; } return ans ; }