Sponsored
Sponsored
This approach involves maintaining a running maximum for the left subarray and a suffix minimum for the right subarray. By iterating through the array and comparing these values, we can determine the appropriate partition point where all conditions are satisfied.
Time Complexity: O(n) - Linear scan of the array.
Space Complexity: O(1) - Only variables used for tracking, no extra storage required.
1public class PartitionArray {
2 public static int partitionDisjoint(int[] nums) {
3 int maxLeft = nums[0], maxSoFar = nums[0], partitionIdx = 0;
4 for (int i = 1; i < nums.length; i++) {
5 if (nums[i] < maxLeft) {
6 maxLeft = maxSoFar;
7 partitionIdx = i;
8 } else if (nums[i] > maxSoFar) {
9 maxSoFar = nums[i];
10 }
11 }
12 return partitionIdx + 1;
13 }
14
15 public static void main(String[] args) {
16 int[] nums = {5, 0, 3, 8, 6};
17 System.out.println(partitionDisjoint(nums)); // Output: 3
18 }
19}
20
This Java solution uses similar logic. The variables maxLeft
and maxSoFar
help determine where the array should split, ensuring that the partition criteria are met. It iterates through the array once to find the partition point.
This approach involves using two additional arrays: one to track the maximum values until any index from the left and another to track minimum values from the right. These auxiliary arrays help determine where a valid partition can be made in the original array.
Time Complexity: O(n) - Needs three linear passes through the array.
Space Complexity: O(n) - Additional space for two auxiliary arrays.
1
Java employs two auxiliary arrays like the other approaches to determine partition points efficiently. Synchronization of leftMax
and rightMin
arrays enables satisfying partition structures.