A milder ending makes the whole thing seem milder
In both exams the pain peaks at 8. One ends while the pain is still at 6; the other goes on a few more minutes and drops to 2 before it ends. Average "the worst" and "the last," and the first exam comes to (8+6)/2=7, the second to (8+2)/2=5. The second is remembered as much milder, even though it was longer. Make the ending a little milder or a little worse, and the overall rating in memory moves almost in step; how long it lasted changes it very little. This is called duration neglect.
The peak and the end are what memory pulls out first
Memory doesn't keep an account of every minute; it keeps only a few snapshots. The most intense moment stands out most. The last moment is closest to when you look back, and it also marks how the whole thing ended, so it is easy to keep too. Duration itself isn't a snapshot, so it hardly enters the memory at all. In Daniel Kahneman's 1993 cold-water experiment, subjects once put a hand in cold water for 60 seconds. Another time they kept it in for 60 seconds, then for 30 more seconds in slightly warmer water. Asked afterward which one to repeat, most chose the longer one whose end wasn't as cold.
A better memory doesn't mean less suffering
In the longer trial, subjects actually put up with 30 more seconds of cold. The rating in memory and the feeling while it happens are two separate accounts, and the peak-end rule describes the one in memory.
The peak-end rule fits best a single experience with a clear beginning and end and feelings that rise and fall within it: an exam, a show, a trip. For a marriage of many years or the same commute every day, no single peak or end can stand for the whole, so the average feeling comes back into play. Some businesses first put customers through misery, then try to make up for it with a gift and an apology at the end. But when the peak itself is awful, an ending like that can't rescue it; and even if the memory gets better, the time and health already spent don't come back.