151 DSA Problem journey

151 DSA Problem journey

Max Chunks To Make Sorted II

Q9: 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 = [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.

Solution:
class Solution {
public:
    int maxChunksToSorted(vector<int>& arr) {

        int n = arr.size();
        vector<int> rightmin(n+1,INT_MAX);
        for(int i=n-1;i>=0;i--)
        {
            rightmin[i] = min(arr[i],rightmin[i+1]);
        }
        int count = 0;
        int leftmax = INT_MIN;
        for(int i=0;i<n;i++)
        {
            leftmax = max(leftmax,arr[i]);
            if(leftmax <= rightmin[i+1])
            {
                count++;
            }
        }
        return count++;        
    }
};
Explantion:
.)n: Size of the input array arr.
.)rightmin:A vector to store the minimum value to the right of each element in arr.
 It is initialized with INT_MAX.
.)Loop through the array in reverse order.
.)rightmin[i]:Update rightmin to store the minimum value between the current element
  arr[i] and the previously stored minimum (rightmin[i+1]).
.)count: Initialize a variable to count the chunks.
.)leftmax:Initialize a variable to store the maximum value encountered from the left, 
  starting with the minimum possible integer value.
.)Loop through the array from left to right.
.)leftmax: Update leftmax to store the maximum value encountered so far from the left.
.)If leftmax is less than or equal to the minimum value to the right of the next element (rightmin[i+1]), 
 it indicates a potential chunk boundary. Increment the count of chunks.
.)Return the count of chunks. Note the post-increment (count++) here doesn't affect the returned value.

>>The function aims to find the maximum number of chunks into which the input array can be 
divided such that each chunk is sorted individually, and the maximum value in the chunk from
the left is less than or equal to the minimum value to the right of the chunk.

##If anyone have better solution so please comment :)

Did you find this article valuable?

Support Gaurav Coding Blogs by becoming a sponsor. Any amount is appreciated!