Why do we reverse in this problem as mentioned in the algorithm?
Algorithm The steps to solve this problem:
- Scan from right to left, find the first element that is less than its previous one.
4 5 6 3 2 1
|
p
- Scan from right to left, find the first element that is greater than p.
4 5 6 3 2 1
|
q
- Swap p and q
4 5 6 3 2 1
swap
4 6 5 3 2 1
- Reverse elements [p+1, nums.length]
4 6 1 2 3 5
What is the logic behind reversing from p+1 to end?