To ensure every element in left is less than or equal to every element in right, we can precompute the maximum value up to each index from the left and the minimum value from each index to the right. The smallest partition point is where the left max is less than or equal to the right min.
classSolution {
publicintpartitionDisjoint(int[] nums) {
int n = nums.length;
int[] leftMax =newint[n], rightMin =newint[n];
leftMax[0]= nums[0];
for (int i = 1; i < n; i++)
leftMax[i]= Math.max(leftMax[i-1], nums[i]);
rightMin[n-1]= nums[n-1];
for (int i = n-2; i >= 0; i--)
rightMin[i]= Math.min(rightMin[i+1], nums[i]);
for (int i = 0; i < n-1; i++) {
if (leftMax[i]<= rightMin[i+1])
return i+1;
}
return n;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
funpartitionDisjoint(nums: IntArray): Int {
val n = nums.size
val leftMax = IntArray(n)
val rightMin = IntArray(n)
leftMax[0] = nums[0]
for (i in1 until n) leftMax[i] = maxOf(leftMax[i-1], nums[i])
rightMin[n-1] = nums[n-1]
for (i in n-2 downTo 0) rightMin[i] = minOf(rightMin[i+1], nums[i])
for (i in0 until n-1) {
if (leftMax[i] <= rightMin[i+1]) return i+1 }
return n
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution:
defpartitionDisjoint(self, nums: list[int]) -> int:
n = len(nums)
left_max = [0] * n
right_min = [0] * n
left_max[0] = nums[0]
for i in range(1, n):
left_max[i] = max(left_max[i-1], nums[i])
right_min[-1] = nums[-1]
for i in range(n-2, -1, -1):
right_min[i] = min(right_min[i+1], nums[i])
for i in range(n-1):
if left_max[i] <= right_min[i+1]:
return i+1return n