$limit = 5;
if ( $query->have_posts() ) :
while ( $query->have_posts() ) :
$query->the_post();
if ( in_array( get_the_ID(), $posts_to_exclude, true ) && $limit > 0 ) {
continue;
}
$limit--;
the_title();
endwhile;
endif;