Transforming an Array to an Odd Array with minimum Cost
Last Updated :
28 Aug, 2023
Given an input array arr[], convert a given array to an 'odd array' consisting of only odd numbers. An even number can be made odd by swapping it with its adjacent element, with a cost equal to the total number of swaps made. If a number cannot be made odd, it can be deleted with a cost of 3, the task is to find the minimum cost to transform the input array to an odd array or determine if it is not possible.
Examples:
Input: arr[] = {126, 32, 16468}
Output: 6
Explanation: For making 126 an odd number we need to perform two swaps 1, 2 and 1, 6. So the cost will be 2. For making 32 an odd number we need to perform one swap 3, 2 only. So the cost will be 1. For making 16468 an odd number, the number of swaps will be 4 so instead of making it odd we can delete it with cost of 3. So total cost will be 2 + 1 + 3 = 6 .
Input: arr[] = {72, 46, 15, 120, 5680}
Output: 9
Explanation: For making 72 an odd number the cost will be 1. 46 cannot be converted into an odd number so we need to delete this and it will cost 3. 15 is already an odd number, so the cost here will be 0. For making 120 an odd number, the cost will be 2. For making 5680 an odd number, the cost will be 3. Total cost will be 1 + 3 + 0 + 2 + 3 = 9.
Approach: The idea is to follow a greedy approach.
Always choose between number of swaps and deletion, whichever costs minimum and add that minimum to the answer.
Below are the steps for the above approach:
- Create a function makeNumberOdd takes an integer as input and returns the cost of converting it into an odd number.
- Initialize a variable cost = 0.
- Run a loop till the number becomes odd or reaches 0.
- Divide the number by 10 and increment the cost by 1, to remove the last digit.
- Check if the number becomes 0 or odd after the loop, and return the cost, or else return -1.
- Initialize a variable minCost = 0.
- Iterate the elements in the vector and calls the makeNumberOdd function for each element.
- If the makeNumberOdd function returns a non-negative cost, add the minimum of 3 and the returned cost to the minimum cost. If it returns -1, add 3 to the minimum cost.
- Return the minimum cost.
Below is the code for the above approach:
C++
// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
int makeNumberOdd(int n)
{
int cost = 0;
// For calculating the cost for
// making the number odd
while (n % 2 != 1 && n > 0) {
// While loop till the number
// becomes odd
n /= 10;
// The last digit is even so we
// remove it to check next digit
// and increment the cost by one.
cost++;
}
if (n == 0 || n % 2 == 0)
// Return -1 if we cannot make the
// current number odd
return -1;
return cost;
}
int makeArrayOdd(vector<int> arr)
{
int minCost = 0;
for (int i = 0; i < arr.size(); i++) {
int cost = makeNumberOdd(arr[i]);
// Function call for
// makeNumberOdd function
if (cost != -1)
minCost += min(3, cost);
// If current element can be
// converted into odd number
else
minCost += 3;
// If current element cannot be
// converted into odd number
// this means we have to delete
// current element which cost 3
}
return minCost;
}
// Driver's code
int main()
{
vector<int> arr{ 72, 46, 15, 120, 5680 };
// Function call
cout << makeArrayOdd(arr);
return 0;
}
Java
// java code for above approach
import java.util.ArrayList;
import java.util.List;
public class Main {
public static int makeNumberOdd(int n)
{
int cost = 0;
// For calculating the cost for
// making the number odd
while (n % 2 != 1 && n > 0) {
// While loop till the number
// becomes odd
n /= 10;
// The last digit is even so we
// remove it to check next digit
// and increment the cost by one.
cost++;
}
if (n == 0 || n % 2 == 0)
// Return -1 if we cannot make the
// current number odd
return -1;
return cost;
}
public static int makeArrayOdd(List<Integer> arr)
{
int minCost = 0;
for (int i = 0; i < arr.size(); i++) {
int cost = makeNumberOdd(arr.get(i));
// Function call for
// makeNumberOdd function
if (cost != -1)
minCost += Math.min(3, cost);
// If current element can be
// converted into odd number
else
minCost += 3;
// If current element cannot be
// converted into odd number
// this means we have to delete
// current element which cost 3
}
return minCost;
}
// Driver's code
public static void main(String[] args)
{
List<Integer> arr = new ArrayList<>();
arr.add(72);
arr.add(46);
arr.add(15);
arr.add(120);
arr.add(5680);
// Function call
System.out.println(makeArrayOdd(arr));
}
}
Python3
# python code for the above approach:
def make_number_odd(n):
cost = 0
# For calculating the cost for making the number odd
while n % 2 != 1 and n > 0:
# While loop till the number becomes odd
n //= 10
# The last digit is even, so we remove it to check the next digit
# and increment the cost by one.
cost += 1
if n == 0 or n % 2 == 0:
# Return -1 if we cannot make the current number odd
return -1
return cost
def make_array_odd(arr):
min_cost = 0
for i in range(len(arr)):
cost = make_number_odd(arr[i])
# Function call for make_number_odd function
if cost != -1:
min_cost += min(3, cost)
else:
# If the current element cannot be converted into an odd number,
# this means we have to delete the current element, which costs 3.
min_cost += 3
return min_cost
# Driver's code
arr = [72, 46, 15, 120, 5680]
# Function call
print(make_array_odd(arr))
C#
using System;
using System.Collections.Generic;
class Program {
static int MakeNumberOdd(int n)
{
int cost = 0;
// For calculating the cost for
// making the number odd
while (n % 2 != 1 && n > 0) {
// While loop till the number
// becomes odd
n /= 10;
// The last digit is even so we
// remove it to check next digit
// and increment the cost by one.
cost++;
}
if (n == 0 || n % 2 == 0) {
// Return -1 if we cannot make the
// current number odd
return -1;
}
return cost;
}
static int MakeArrayOdd(List<int> arr)
{
int minCost = 0;
for (int i = 0; i < arr.Count; i++) {
int cost = MakeNumberOdd(arr[i]);
// Function call for
// makeNumberOdd function
if (cost != -1) {
minCost += Math.Min(3, cost);
}
// If current element can be
// converted into odd number
else {
minCost += 3;
}
// If current element cannot be
// converted into odd number
// this means we have to delete
// current element which cost 3
}
return minCost;
}
// Driver's code
static void Main(string[] args)
{
List<int> arr
= new List<int>{ 72, 46, 15, 120, 5680 };
// Function call
Console.WriteLine(MakeArrayOdd(arr));
}
}
JavaScript
const makeNumberOdd = (n) => {
let cost = 0;
// For calculating the cost for
// making the number odd
while (n % 2 !== 1 && n > 0) {
// While loop till the number
// becomes odd
n = Math.floor(n / 10);
// The last digit is even so we
// remove it to check next digit
// and increment the cost by one.
cost++;
}
if (n === 0 || n % 2 === 0){
// Return -1 if we cannot make the
// current number odd
return -1;
}
return cost;
}
const makeArrayOdd = (arr) => {
let minCost = 0;
for (let i = 0; i < arr.length; i++) {
let cost = makeNumberOdd(arr[i]);
// Function call for
// makeNumberOdd function
if (cost !== -1)
minCost += Math.min(3, cost);
// If current element can be
// converted into odd number
else
minCost += 3;
// If current element cannot be
// converted into odd number
// this means we have to delete
// current element which cost 3
}
return minCost;
}
// Driver's code
const arr = [72, 46, 15, 120, 5680];
console.log(makeArrayOdd(arr));
Time Complexity: O(N), where N is the size of the input array
Auxiliary Space: O(1)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read