Problem of the day
You are given an array ‘A’ containing ‘N’ positive integers.
You define a beautiful distribution of an array as follows.
1. Split the array into multiple groups.
2. Each element of the array is present in exactly one group.
3. If you individually sort each group, the array ‘A’ should also become sorted.
Here, groups means a consecutive set of array ‘A’ elements.
There can be multiple beautiful distributions, so you are interested in the one where the number of groups is maximized.
Your task is to find the maximum number of groups possible in a beautiful distribution.
Example :‘N’ = 5, ‘A’ = [2, 1, 4, 4 ,3]
Here we can form 2 groups, ‘[2, 1]’ and ‘[4, 4, 3]’. After individually sorting them, the array will be ‘[1, 2, 3, 4, 4]’ and is sorted. And it can be proved that this is the best answer.
Hence, the answer is 2.
The first line contains a single integer ‘T’ denoting the number of test cases, then the test case follows.
The first line of each test case contains a single integer, ‘N'.
The following line contains ‘N’ single space-separated integers, denoting the array ‘A’.
Output Format :
For each test case, return the maximum number of groups in a beautiful distribution.
Output for each test case will be printed on a separate line.
Note :
You are not required to print anything; it has already been taken care of. Just implement the function.
1 ≤ T ≤ 10
1 ≤ N ≤ 10^5
1 ≤ A[i] ≤ 10^9
It’s guaranteed that sum of ‘N’ over all cases doesn’t exceed 10^5.
Time limit: 1 sec
2
5
2 3 5 3 5
5
3 3 3 4 4
4
5
For test case 1:
We can create the 4 groups in the following way: [2], [3], [5, 3], and [5]. If we sort all groups, [5 3] will become [3 5], and the final array will be sorted.
Hence, the answer is 4.
For test case 2:
The array is already sorted so that we can create ‘N’ groups, each group consisting of a single element.
Hence, the answer is 5.
2
4
2 1 3 2
6
4 3 3 2 3 4
2
2
Which condition must be followed if a group ends at the ‘ith’ index?
Approach:
Algorithm:
O(N), Here, 'N' is the number of elements in array 'A'.
We are iterating over each array element twice, so the time complexity is linear.
Hence, the time complexity is O(N).
O(N), Here, 'N' is the number of elements in array 'A'.
The suffix minimum array will take O(N) space. Everything else is constant.
Hence, the space complexity is O(N).