Minimize cost to reduce Array if for choosing every 2 elements, 3rd one is chosen for free
Given an array arr[]. The task is to minimize the cost of reducing the array with a given operation. In one operation choose two elements add their value to the total cost and remove them and remove any other element with a value almost the two chosen elements.
Examples:
Input: arr[] = {1, 2, 3}
Output: 5
Explanation: Choose 2 and 3, cost = 5. 1 is reduced from array for free.
Input: arr[] = {6, 5, 7, 9, 2, 2}
Output: 23
Approach: This problem can be solved by using the Greedy Approach. Follow the steps below to solve the given problem.
- Sort the given array.
- Traverse the sorted array from the end.
- Add 2 elements to the final cost and skip the 3rd one.
- Return the final cost.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int minCost(vector< int >& arr)
{
sort(arr.begin(), arr.end());
int ans = 0;
for ( int i = arr.size() - 1, k = 1;
i >= 0;
i--, k++)
if (k == 3)
k = 0;
else
ans += arr[i];
return ans;
}
int main()
{
vector< int > arr = { 6, 5, 7, 9, 2, 2 };
cout << minCost(arr);
return 0;
}
|
Java
import java.util.*;
class GFG
{
public static int minCost(ArrayList<Integer> arr)
{
Collections.sort(arr);
int ans = 0 ;
for ( int i = arr.size() - 1 , k = 1 ; i >= 0 ;
i--, k++)
if (k == 3 )
k = 0 ;
else
ans += arr.get(i);
return ans;
}
public static void main(String[] args)
{
ArrayList<Integer> arr = new ArrayList<>(
Arrays.asList( 6 , 5 , 7 , 9 , 2 , 2 ));
System.out.print(minCost(arr));
}
}
|
Python3
def minCost(arr):
arr.sort()
ans = 0
k = 1
for i in range ( len (arr) - 1 , 0 , - 1 ):
if k = = 3 :
k = 0
else :
ans = ans + arr[i]
k = k + 1
return ans
arr = [ 6 , 5 , 7 , 9 , 2 , 2 ]
print (minCost(arr))
|
C#
using System;
class GFG
{
static int minCost( int [] arr)
{
Array.Sort(arr);
int ans = 0;
for ( int i = arr.Length - 1, k = 1; i >= 0;
i--, k++)
if (k == 3)
k = 0;
else
ans += arr[i];
return ans;
}
public static void Main()
{
int [] arr = { 6, 5, 7, 9, 2, 2 };
Console.Write(minCost(arr));
}
}
|
Javascript
<script>
const minCost = (arr) => {
arr.sort();
let ans = 0;
for (let i = arr.length - 1, k = 1;
i >= 0;
i--, k++)
if (k == 3)
k = 0;
else
ans += arr[i];
return ans;
}
let arr = [6, 5, 7, 9, 2, 2];
document.write(minCost(arr));
</script>
|
Time Complexity: O(N*log N)
Auxiliary Space: O(1)
Last Updated :
10 Feb, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...