![]() |
VOOZH | about |
Given an array A[] length N along with an integer K. Select a subarray of size K and replace all elements with X (Cross), which has a minimum value in that subarray. Then the task is to output the minimum number of operations required to convert all the elements into X.
Note:
- If there are elements which are already replaced with X, then leave them and apply operation on rest of the elements.
- If there are multiple elements with same minimum value, then replace all of them with X.
Examples:
Input: N = 5, K = 3, A[] = {50, 40, 50, 40, 50}
Output: 3
Explanation:
- First operation: Choose subarray A[2, 4], which has a length equal to 3. So, A[2, 4] = {40, 50, 40}. The minimum value is 40. Therefore, replace all 40 with X in this subarray. Then, A[2, 4] = {X, 50, X}. Now, A[] = {50, X, 50, X, 50}
- Second operation: Choose subarray A[1, 3], which has a length equal to 3. So, A[1, 3] = {50, X, 50}. The minimum value is 50. Therefore, replace all 50 with X in this subarray. Then, A[1, 3] = {X, X, X}. Now, A[] = {X, X, X, X, 50}
- Third operation: Choose subarray A[3, 5], which has a length equal to 3. So, A[3, 5] = {X, X, 50}. The minimum value is 50. Therefore, replace 50 with X in this subarray. Then, A[1, 3] = {X, X, X}. Now, A[] = {X, X, X, X, X}
Now, it can be verified that all the elements are replaced with X (Cross). Therefore, minimum number of operations are required is 3.
Input: N = 3, K = 2, A[] = {10, 20, 20}
Output: 2
Explanation: It can be verified that minimum number of operations required will be 2.
Approach: Implement the idea below to solve the problem
The problem is based on Greedy logic and can be solved by using some observations. For solving this problem, we have to use ArrayList and HashMap. ArrayList will be used to store distinct elements and HashMap will store the indices of elements, which appears more than once.
Steps were taken to solve the problem:
Code to implement the approach:
2
Time Complexity: O(N)
Auxiliary Space: O(N), As HashMap and ArrayList are used.