<p>Given an integer array <code>nums</code>, partition it into two (contiguous) subarrays <code>left</code> and <code>right</code> so that:</p>

<ul>
	<li>Every element in <code>left</code> is less than or equal to every element in <code>right</code>.</li>
	<li><code>left</code> and <code>right</code> are non-empty.</li>
	<li><code>left</code> has the smallest possible size.</li>
</ul>

<p>Return <em>the length of </em><code>left</code><em> after such a partitioning</em>.</p>

<p>Test cases are generated such that partitioning exists.</p>

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

<pre>
<strong>Input:</strong> nums = [5,0,3,8,6]
<strong>Output:</strong> 3
<strong>Explanation:</strong> left = [5,0,3], right = [8,6]
</pre>

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

<pre>
<strong>Input:</strong> nums = [1,1,1,0,6,12]
<strong>Output:</strong> 4
<strong>Explanation:</strong> left = [1,1,1,0], right = [6,12]
</pre>

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

<ul>
	<li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>0 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li>
	<li>There is at least one valid answer for the given input.</li>
</ul>

class Solution {
public:
    int partitionDisjoint(vector<int>& nums) {
        // Suppose we pick a point x that splits the left and right subarrays

        int n = nums.size();

        // Both subarrays must be nonempty, so if we make left = nums[0...x] and right = nums[x + 1... n - 1]
        // Then the valid values of x are 0 to n - 2 inclusive (when x == 0 left is nonempty size 1, whgen x == n - 2
        // right is nonempty size 1)



        // How can we check in efficient time whether left and right meet constraints for choice of x?
        // max_element_left <= min_element_right


        vector<int> max_element_up_to; // max element up to index i 
        int maxSoFar = 0;
        for(int i = 0; i < nums.size(); i++) {
            maxSoFar = max(maxSoFar, nums[i]);
            max_element_up_to.push_back(maxSoFar);

        }


        int minSoFar = INT_MAX;
        vector<int> min_element_from(n, INT_MAX);

        for(int i = n - 1; i >= 0; i--) {
            minSoFar = min(minSoFar, nums[i]);
            min_element_from[i] = minSoFar;
        }


        int bestLenLeft = n;

        for(int x = 0; x <= n - 2; x++) {
            if(max_element_up_to[x] <= min_element_from[x + 1]) {
                return x + 1;
            }
        }


        return bestLenLeft;




    }
};
111200