Sort and trim the ends
class Solution: def minimizeSum(self, nums): values = sorted(nums) n = len(values) best = values[-1] - values[0] for drop_left in range(3): drop_right = 2 - drop_left # 2 changes split over ends spread = values[n - 1 - drop_right] - values[drop_left] best = min(best, spread) return best # low score is 0: changes copy a kept value
The code from the episode, ready for LeetCode's Python 3 editor: paste it in and submit.
Five engines in a snowy rail yard show how changing the smallest and largest numbers can leave a wider gap. Watch how comparing three ways to split the changes between the ends finds the minimum score.
class Solution: def minimizeSum(self, nums): # Set both changed numbers equal to a kept one: low score is 0, # so the score is just the spread (max - min) of what we keep. n = len(nums) best = None for i in range(n): for j in range(i + 1, n): kept = [nums[k] for k in range(n) if k != i and k != j] spread = max(kept) - min(kept) if best is None or spread < best: best = spread return best