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#:
Complexity: O(n)
No comments:
Post a Comment