If you're interested, that question is most commonly referred to in philosophy as the "trolley problem". [1]
It's actually a huge area of philosophical debate. So while the bad news is there's no straightforward answer -- instead there's deep disagreement among philosophers who think about exactly this for a living -- the good news is you could spend literal weeks learning about the arguments on both sides if you wanted to.