Untitled

 avatar
unknown
plain_text
22 days ago
1.2 kB
1
Indexable
public class PartitionArrayDisjointIntervals {
    public int partitionDisjoint(int[] nums) {
        int n = nums.length;

        // Step 1: Create prefixMax array
        int[] prefixMax = new int[n];
        prefixMax[0] = nums[0];
        for (int i = 1; i < n; i++) {
            prefixMax[i] = Math.max(prefixMax[i - 1], nums[i]);
        }

        // Step 2: Create suffixMin array
        int[] suffixMin = new int[n];
        suffixMin[n - 1] = nums[n - 1];
        for (int i = n - 2; i >= 0; i--) {
            suffixMin[i] = Math.min(suffixMin[i + 1], nums[i]);
        }

        // Step 3: Find the partition index
        for (int i = 0; i < n - 1; i++) {
            if (prefixMax[i] <= suffixMin[i + 1]) {
                return i + 1; // Return the length of the left subarray
            }
        }

        // This point will not be reached as per problem constraints
        return -1;
    }

    public static void main(String[] args) {
        PartitionArrayDisjointIntervals obj = new PartitionArrayDisjointIntervals();
        int[] nums = {5, 0, 3, 8, 6};
        System.out.println("Length of the left subarray: " + obj.partitionDisjoint(nums));
    }
}
Leave a Comment