US stocks end with gains as Nasdaq, S&P hit record highs