Partition Array into Disjoint Intervals

medium array prefix max partition

Problem

Given an integer array nums, partition it into two contiguous parts left and right so that every element in left is less than or equal to every element in right, and left is as small as possible. Both parts must be non-empty. Return the length of left. A valid partition is guaranteed to exist.

Inputnums = [5, 0, 3, 8, 6]
Output3
left = [5, 0, 3], right = [8, 6]. Every left value (max 5) is ≤ every right value (min 6).

def partition_disjoint(nums):
    left_max = cur_max = nums[0]
    length = 1
    for i in range(1, len(nums)):
        if nums[i] < left_max:
            length = i + 1
            left_max = cur_max
        else:
            cur_max = max(cur_max, nums[i])
    return length
function partitionDisjoint(nums) {
  let leftMax = nums[0], curMax = nums[0];
  let length = 1;
  for (let i = 1; i < nums.length; i++) {
    if (nums[i] < leftMax) {
      length = i + 1;
      leftMax = curMax;
    } else {
      curMax = Math.max(curMax, nums[i]);
    }
  }
  return length;
}
class Solution {
    public int partitionDisjoint(int[] nums) {
        int leftMax = nums[0], curMax = nums[0];
        int length = 1;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] < leftMax) {
                length = i + 1;
                leftMax = curMax;
            } else {
                curMax = Math.max(curMax, nums[i]);
            }
        }
        return length;
    }
}
int partitionDisjoint(vector<int>& nums) {
    int leftMax = nums[0], curMax = nums[0];
    int length = 1;
    for (int i = 1; i < (int)nums.size(); i++) {
        if (nums[i] < leftMax) {
            length = i + 1;
            leftMax = curMax;
        } else {
            curMax = max(curMax, nums[i]);
        }
    }
    return length;
}
Time: O(n) Space: O(1)