Monday, December 19, 2022

[LeetCode] Max Chunks To Make Sorted II

Problem: You are given an integer array arr.

We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.

Return the largest number of chunks we can make to sort the array.

Example:

Input: arr = [5,4,3,2,1]
Output: 1
Explanation:
Splitting into two or more chunks will not return the required result.
For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted.
Input: arr = [2,1,3,4,4]
Output: 4
Explanation:
We can split into two chunks, such as [2, 1], [3, 4, 4].
However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.


Approach: Here we can use chaining technique. We can have one array which stores the max from left and one array which stores the min from the right. At any index 'i' if we find that 

leftMax[i] <= rightMin[i + 1] 

then we can safely consider it as a chunk. Right? Confusing, isn't it? Let's taken an example and see. 

Let's take an array arr =  [30, 20, 10, 40, 60, 50, 70]. It's leftMax and rightMin will be:

lmax = [30, 30, 30, 40, 60, 60, 70]

rmin = [10 ,10, 10, ,40, 50, 50, 70]

if lmax[i] is greater than rightMin[i + 1] then it means they can be in the same chunk because that means till now the array has the right elements till index 'i'.


Implementation in C#:

    public int MaxChunksToSorted(int[] arr)
    {
        int length = arr?.Length ?? 0;
        if (length <= 1)
        {
            return length;
        }
        int[] rightMin = new int[length];
        rightMin[length - 1] = arr[length - 1];
        for (int i = length - 2; i >= 0; --i)
        {
            rightMin[i] = Math.Min(rightMin[i + 1], arr[i]);
        }
        int chunksRequired = 1;
        int lmax = -1;
        for (int i = 0; i < length - 1; ++i)
        {
            lmax = Math.Max(lmax, arr[i]);
            if (lmax <= rightMin[i + 1])
            {
                ++chunksRequired;
            }
        }
        return chunksRequired;
    }

Complexity: O(n)

No comments:

Post a Comment