Minimum cost required to move all elements to the same position
Last Updated :
17 Apr, 2023
Given an array position[] consisting of N integers where position[i] denotes the position of the ith element, the task is to find the minimum cost required to move all the elements to the same position by performing either of the following two operations:
- Move from position[i] to position[i] + 2 or position[i] – 2. Cost = 0.
- Move from position[i] to position[i] + 1 or position[i] – 1. Cost = 1.
Examples:
Input: position[] = {1, 2, 3}
Output: 1
Explanation:
Operation 1: Move the element at position 3 to position 1. Cost = 0.
Operation 2: Move the element at position 2 to position 1. Cost = 1.
Therefore, total cost = 1.
Input: position[] = {2, 2, 2, 3, 3}
Output: 2
Explanation: Move the two elements at position 3 to position 2. Cost of each operation = 1. Therefore, total cost = 2.
Approach: The idea is to traverse the array and count the number of odd and even elements. For each operation involving increment or decrement by two indices, the cost will always be 0. The cost changes only on moving an element from odd to even position or vice-versa. Therefore, the minimum cost required is the minimum of the count of odd and even elements present in the array position[].
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int minCost( int arr[], int arr_size)
{
int odd = 0, even = 0;
for ( int i = 0; i < arr_size; i++)
{
if (arr[i] % 2 == 0)
even++;
else
odd++;
}
cout << min(even, odd);
}
int main()
{
int arr[] = { 1, 2, 3 };
int arr_size = sizeof (arr) / sizeof (arr[0]);
minCost(arr, arr_size);
}
|
Java
import java.io.*;
class GFG {
public void minCost( int [] arr)
{
int odd = 0 , even = 0 ;
for ( int i = 0 ;
i < arr.length; i++) {
if (arr[i] % 2 == 0 )
even++;
else
odd++;
}
System.out.print(
Math.min(even, odd));
}
public static void main(String[] args)
{
GFG obj = new GFG();
int arr[] = { 1 , 2 , 3 };
obj.minCost(arr);
}
}
|
Python3
def minCost(arr):
odd = 0
even = 0
for i in range ( len (arr)):
if (arr[i] % 2 = = 0 ):
even + = 1
else :
odd + = 1
print ( min (even, odd))
if __name__ = = '__main__' :
arr = [ 1 , 2 , 3 ]
minCost(arr)
|
C#
using System;
class GFG{
public void minCost( int [] arr)
{
int odd = 0, even = 0;
for ( int i = 0; i < arr.Length; i++)
{
if (arr[i] % 2 == 0)
even++;
else
odd++;
}
Console.Write(Math.Min(even, odd));
}
public static void Main()
{
GFG obj = new GFG();
int [] arr = { 1, 2, 3 };
obj.minCost(arr);
}
}
|
Javascript
<script>
function minCost(arr)
{
let odd = 0, even = 0;
for (let i = 0;
i < arr.length; i++) {
if (arr[i] % 2 == 0)
even++;
else
odd++;
}
document.write(
Math.min(even, odd));
}
let arr = [ 1, 2, 3 ];
minCost(arr);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...