Minimum cost to make array size 1 by removing larger of pairs
Last Updated :
18 Sep, 2023
Given an array of n integers. We need to reduce size of array to one. We are allowed to select a pair of integers and remove the larger one of these two. This decreases the array size by 1. Cost of this operation is equal to value of smaller one. Find out minimum sum of costs of operations needed to convert the array into a single element.
Examples:
Input: 4 3 2
Output: 4
Explanation:
Choose (4, 2) so 4 is removed, new array
= {2, 3}. Now choose (2, 3) so 3 is removed.
So total cost = 2 + 2 = 4
Input: 3 4
Output: 3
Explanation: choose 3, 4, so cost is 3.
The idea is to always pick minimum value as part of the pair and remove larger value. This minimizes cost of reducing array to size 1.
Below is the implementation of the above approach:
CPP
#include <bits/stdc++.h>
using namespace std;
int cost( int a[], int n)
{
return (n - 1) * (*min_element(a, a + n));
}
int main()
{
int a[] = { 4, 3, 2 };
int n = sizeof (a) / sizeof (a[0]);
cout << cost(a, n) << endl;
return 0;
}
|
Java
import java.lang.*;
public class GFG {
static int cost( int []a, int n)
{
int min = a[ 0 ];
for ( int i = 1 ; i< a.length; i++)
{
if (a[i] < min)
min = a[i];
}
return (n - 1 ) * min;
}
static public void main (String[] args)
{
int []a = { 4 , 3 , 2 };
int n = a.length;
System.out.println(cost(a, n));
}
}
|
Python3
def cost(a, n):
return ( (n - 1 ) * min (a) )
a = [ 4 , 3 , 2 ]
n = len (a)
print (cost(a, n))
|
C#
using System;
using System.Linq;
public class GFG {
static int cost( int []a, int n)
{
return (n - 1) * a.Min();
}
static public void Main (){
int []a = { 4, 3, 2 };
int n = a.Length;
Console.WriteLine(cost(a, n));
}
}
|
PHP
<?php
function cost( $a , $n )
{
return ( $n - 1) * (min( $a ));
}
$a = array (4, 3, 2);
$n = count ( $a );
echo cost( $a , $n );
?>
|
Javascript
<script>
function cost(a, n)
{
let min = a[0];
for (let i = 1; i< a.length; i++)
{
if (a[i] < min)
min = a[i];
}
return (n - 1) * min;
}
let a = [ 4, 3, 2 ];
let n = a.length;
document.write(cost(a, n));
</script>
|
Time Complexity: O(N), as we are using a min function which will cost O(N).
Auxiliary Space: O(1), as we are not using any extra space.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...