Sorting the input often makes the structure visible: the answer depends only on the multiset, or the optimal object is sorted, or elements that cannot pass each other keep their relative order.

FactStatement
adjacent swaps to sortexactly the number of inversions
arbitrary swaps to sort a permutation
sort by “move an element to the front” (longest suffix of the sorted order that already appears as a subsequence in order, ending at the largest)
sort by reversing prefixes (pancakes)at most flips
relative orderelements that only swap with neighbours, or bounce off each other, keep their order
exchange argumentsort by the key that makes swapping adjacent elements never improve the answer
”choose elements” problemsafter sorting, the optimal choice is often contiguous or a prefix plus a suffix

Ants on a stick

ants on a stick of length at distinct integer positions, each walking left or right at speed 1; when two meet they both turn around. Over all direction choices, what are the earliest and latest times the last ant falls off?

Turning around is indistinguishable from passing through (only labels swap), so each ant’s “ghost” walks straight. Hence:

pair<int, int> antsTimes(int L, const vector<int>& x) {   // {earliest, latest} time the last ant falls
    int lo = 0, hi = 0;
    for (int v : x) lo = max(lo, min(v, L - v)), hi = max(hi, max(v, L - v));
    return {lo, hi};
}

Patterns

StatementObservation
”the order of operations does not matter”sort the operations by the cheapest order, or count instead of simulate
”choose pairs to minimise the maximum pair sum”sort and pair smallest with largest
”minimise $\suma_i - x
”minimise ” is the mean
”make the array non-decreasing by increments”prefix maxima; the cost is
“cyclic shifts”double the array, or fix the rotation that puts the minimum first

Related: Sorting, Exchange Arguments.