Problem. Sort a stack by prefix reversals (flip the top pancakes).

Answer: at most flips: bring the largest unsorted pancake to the top, then flip it into place. The exact minimum is NP-hard in general; known bounds are worst case .

vector<int> pancakeSort(vector<int>& a) {         // returns flip lengths (reverse prefix of that length); at most 2n - 3 flips
    vector<int> flips; int n = sz(a);
    for (int len = n; len > 1; len--) {
        int m = max_element(a.begin(), a.begin() + len) - a.begin();
        if (m == len - 1) continue;
        if (m > 0) { reverse(a.begin(), a.begin() + m + 1); flips.push_back(m + 1); }
        reverse(a.begin(), a.begin() + len); flips.push_back(len);
    }
    return flips;
}