Skip to content

Conversation

@cypher-00-00
Copy link

class Solution {
public:
vector pancakeSort(vector& arr) {
vector res;
for (int n = arr.size(); n > 1; n--) {
// find index of max element in arr[0..n-1]
int maxIdx = max_element(arr.begin(), arr.begin() + n) - arr.begin();

        if (maxIdx == n - 1) continue; // already in place

        // Step 1: flip max element to front
        if (maxIdx > 0) {
            reverse(arr.begin(), arr.begin() + maxIdx + 1);
            res.push_back(maxIdx + 1);
        }

        // Step 2: flip it to its correct position
        reverse(arr.begin(), arr.begin() + n);
        res.push_back(n);
    }
    return res;
}

};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant