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:
- Create an ArrayList let say List to store distinct elements.
- Create a HashMap of <Integer, ArrayList<Integer>> type let say Map to store the list of indices of a element.
- sort the List so that minimum elements removed first.
- For each element traverse the indices and calculate the number of operations to remove all the occurrences of element.
- Output the value of minimum number of operations.
Code to implement the approach:
// C++ code to implement the approach #include <bits/stdc++.h> using namespace std;
// Function to calculate minimum operations void min_operations( int N, int K, vector< int >& A)
{ // Declaring a map to store the indices of elements
map< int , vector< int > > map;
// Declaring a vector to store unique elements
vector< int > list;
// Iterating through the array and populating the map
// and list
for ( int i = 0; i < N; i++) {
int num = A[i];
if (map.find(num) == map.end()) {
map[num] = vector< int >();
list.push_back(num);
}
map[num].push_back(i);
}
// Sorting the list in ascending order
sort(list.begin(), list.end());
int min = 0;
for ( int i : list) {
int prev = map[i][0];
min++;
for ( int j : map[i]) {
if (j >= (prev + K)) {
min++;
prev = j;
}
}
}
cout << min << endl;
} int main()
{ // Inputs
int N = 3;
int K = 2;
vector< int > A = { 10, 20, 20 };
// Function call
min_operations(N, K, A);
return 0;
} |
import java.util.*;
class Main {
// Function to calculate minimum operations
public static void min_operations( int N, int K, int [] A)
{
// Declaring an ArrayList
List<Integer> list = new ArrayList<>();
// Declaring a HashMap
HashMap<Integer, ArrayList<Integer>> map = new HashMap<>();
// Run a loop for each element
for ( int i = 0 ; i < N; i++) {
int num = A[i];
if (!map.containsKey(num)) {
map.put(num, new ArrayList<>());
list.add(num);
}
map.get(num).add(i);
}
// Sorting list using in-built sort function
Collections.sort(list);
int min = 0 ;
for ( int i : list) {
int prev = map.get(i).get( 0 );
min++;
for ( int j : map.get(i)) {
if (j >= (prev + K)) {
min++;
prev = j;
}
}
}
System.out.println(min);
}
// Driver Class
public static void main(String args[])
{
// Inputs
int N = 3 ;
int K = 2 ;
int A[] = { 10 , 20 , 20 };
// Function call
min_operations(N, K, A);
}
} |
# Function to calculate minimum operations def min_operations(N, K, A):
# Declaring a dictionary to store the indices of elements
index_map = {}
# Declaring a list to store unique elements
unique_list = []
# Iterating through the array and populating the dictionary and list
for i in range (N):
num = A[i]
if num not in index_map:
index_map[num] = []
unique_list.append(num)
index_map[num].append(i)
# Sorting the list in ascending order
unique_list.sort()
min_ops = 0
for i in unique_list:
prev = index_map[i][ 0 ]
min_ops + = 1
for j in index_map[i]:
if j > = (prev + K):
min_ops + = 1
prev = j
print (min_ops)
# Main function if __name__ = = "__main__" :
# Inputs
N = 3
K = 2
A = [ 10 , 20 , 20 ]
# Function call
min_operations(N, K, A)
|
using System;
using System.Collections.Generic;
using System.Linq;
class GFG
{ // Function to calculate minimum operations
static void MinOperations( int N, int K, List< int > A)
{
// Declaring a dictionary to store the indices of elements
Dictionary< int , List< int >> map = new Dictionary< int , List< int >>();
// Declaring a list to store unique elements
List< int > list = new List< int >();
// Iterating through the array and populating the map and list
foreach ( int i in Enumerable.Range(0, N))
{
int num = A[i];
if (!map.ContainsKey(num))
{
map[num] = new List< int >();
list.Add(num);
}
map[num].Add(i);
}
// Sorting the list in ascending order
list.Sort();
int min = 0;
foreach ( int i in list)
{
int prev = map[i][0];
min++;
foreach ( int j in map[i])
{
if (j >= (prev + K))
{
min++;
prev = j;
}
}
}
Console.WriteLine(min);
}
static void Main( string [] args)
{
// Inputs
int N = 3;
int K = 2;
List< int > A = new List< int > { 10, 20, 20 };
// Function call
MinOperations(N, K, A);
}
} |
// Function to calculate minimum operations function minOperations(N, K, A) {
// Declaring a map to store the indices of elements
let map = new Map();
// Declaring a set to store unique elements
let list = [];
// Iterating through the array and populating the map and list
for (let i = 0; i < N; i++) {
let num = A[i];
if (!map.has(num)) {
map.set(num, []);
list.push(num);
}
map.get(num).push(i);
}
// Sorting the list in ascending order
list.sort((a, b) => a - b);
let min = 0;
for (let i of list) {
let prev = map.get(i)[0];
min++;
for (let j of map.get(i)) {
if (j >= prev + K) {
min++;
prev = j;
}
}
}
console.log(min);
} // Inputs let N = 3; let K = 2; let A = [10, 20, 20]; // Function call minOperations(N, K, A); |
// Function to calculate minimum operations void minOperations( int N, int K, List< int > A) {
// Declaring a map to store the indices of elements
Map< int , List< int >> map = {};
// Declaring a list to store unique elements
List< int > list = [];
// Iterating through the array and populating the map and list
for ( int i = 0; i < N; i++) {
int num = A[i];
if (!map.containsKey(num)) {
map[num] = [];
list.add(num);
}
map[num]!.add(i);
}
// Sorting the list in ascending order
list.sort();
int min = 0;
for ( int i in list) {
int prev = map[i]![0]!;
min++;
for ( int j in map[i]!) {
if (j >= (prev + K)) {
min++;
prev = j;
}
}
}
print(min);
} void main() {
// Inputs
int N = 3;
int K = 2;
List< int > A = [10, 20, 20];
// Function call
minOperations(N, K, A);
} |
2
Time Complexity: O(N)
Auxiliary Space: O(N), As HashMap and ArrayList are used.