<p>Given an array of positive integers <code>arr</code> (not necessarily distinct), return <em>the </em><span data-keyword="lexicographically-smaller-array"><em>lexicographically</em></span><em> largest permutation that is smaller than</em> <code>arr</code>, that can be <strong>made with exactly one swap</strong>. If it cannot be done, then return the same array.</p>

<p><strong>Note</strong> that a <em>swap</em> exchanges the positions of two numbers <code>arr[i]</code> and <code>arr[j]</code></p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> arr = [3,2,1]
<strong>Output:</strong> [3,1,2]
<strong>Explanation:</strong> Swapping 2 and 1.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> arr = [1,1,5]
<strong>Output:</strong> [1,1,5]
<strong>Explanation:</strong> This is already the smallest permutation.
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> arr = [1,9,4,6,7]
<strong>Output:</strong> [1,7,4,6,9]
<strong>Explanation:</strong> Swapping 9 and 7.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= arr.length &lt;= 10<sup>4</sup></code></li>
	<li><code>1 &lt;= arr[i] &lt;= 10<sup>4</sup></code></li>
</ul>

class Solution {
public:
    vector<int> prevPermOpt1(vector<int>& arr) {
        // brute force is n^2
        // can probably do linear or n log n

        // if i have [2, 1, 0] i want to swap last two, for [2, 0, 1]
        // maybe swap rightmost pair of i, (i + 1) where arr[i] > arr[i + 1]

        // i is the rightmost i where arr[i] > arr[i + 1]. in that case, j will be the largest arr[j] where i < j < arr.size() and arr[j] < arr[i].

        int left_index = arr.size() - 2;
        for (; left_index >= 0; --left_index)
            if (arr[left_index] > arr[left_index + 1])
                break;

        // no smaller permutations with a single swap exist
        if (left_index < 0)
            return std::move(arr);

        int right_index = -1;
        for (int i = left_index + 1; i < arr.size(); ++i) {
            if (arr[i] < arr[left_index] && (right_index == -1 || arr[i] > arr[right_index]))
                right_index = i;
        }
        assert(right_index != -1);

        std::swap(arr[left_index], arr[right_index]);
        return std::move(arr);
    }
};
26600