![]() |
VOOZH | about |
Given an array arr[] of size n such that elements of arr[] in range [0, 1, ..n-1] where every number is present at most once. Our task is to divide the array into maximum number of partitions that can be sorted individually, then concatenated to make the whole array sorted.
Examples :
Input : arr[] = [2, 1, 0, 3]
Output : 2
If divide arr[] into two partitions
{2, 1, 0} and {3}, sort them and concatenate
then, we get the whole array sorted.
Input : arr[] = [2, 1, 0, 3, 4, 5]
Output : 4
The maximum number of partitions are four, we
get these partitions as {2, 1, 0}, {3}, {4}
and {5}
Input : arr[] = [0, 1, 2, 3, 4, 5]
Output : 6
The maximum number of partitions are six, we
get these partitions as {0}, {1}, {2}, {3}, {4}
and {5}
Approach:
The given code finds the maximum number of partitions that can be made from an array of integers. The code defines a function "maxPartitions" that takes an array and its length as input. The function then uses a loop to iterate through each element of the array and find the maximum element in the prefix ending at the current index. If the maximum element is equal to the current index, the function increments the count of partitions as a new partition can be made ending at that index. Finally, the function returns the count of partitions. The main function initializes an array with values and calls the "maxPartitions" function with the array and its length as inputs. The result of the function is then printed to the console.
Algorithm to find maximum partitions:
The idea is based on the fact that if an element at i is maximum of prefix arr[0..i], then we can make a partition ending with i.
4
Time Complexity: O(N)
Auxiliary Space: O(1)