Skip to content
Related Articles

Related Articles

Improve Article

Merge K minimum elements of the array until there is only one element

  • Last Updated : 07 May, 2020
Geek Week

Given an array arr[] and an integer K, the task is to merge K minimum elements of the array until there is only one element left in the array.

Note: If it is impossible to merge into only one element then print -1.

Input: arr[] = {3, 2, 4, 1}, K = 2
Output: 10
Explanation:
Merge K minimum elements of the Array({3, 2, 4, 1}) = 1 + 2 = 3
After Mergeing the Array will be {3, 3, 4}
Merge K minimum elements of the Array ({3, 3, 4}) = 3 + 3 = 6
After Merging the Array will be {4, 6}
Merge K minimum elements of the Array ({4, 6}) = 4 + 6 = 10

Input: arr[] = {3, 2, 4, 1}, K = 3
Output: -1
Explanation:
After merging there will be two elements left {6, 4} which cannot be merged further.

Approach: The idea is to sort the array and then merge the first K minimum elements of the array into one element, then insert the element into the array at its sorted position into the array with the help of the Binary Search. Similarly, repeat this step until there is only one element left in the array. If in the end there are less than K elements left then return -1.



Below is the implementation of the above approach:

Java




// Java implementation to merge the
// K minimum elements of the Array
// until there is only one element
// is left in the array
  
// Imports
import java.io.*;
import java.lang.*;
import java.util.*;
  
  
class GFG {
      
    // Function to merge the element
    // of the array until there is
    // only one element left in array
    public static int mergeStones(
        List<Integer> list, final int k) {
          
        // Sorting the array
        Collections.sort(list);
        int cost = 0;
          
        // Loop to merge the elements
        // until there is element
        // greater than K elements
        while(list.size() > k) {
            int sum = 0;
              
            // Merging the K minimum 
            // elements of the array
            for(int i = 0; i < k; i++) {
                sum += list.get(i);
            }
              
            // Removing the K minimum 
            // elements of the array
            list.subList(0, k).clear();
              
            // Inserting the merged 
            // element into the array
            insertInSortedList(list, sum); 
            cost += sum;
        }
          
        // If there is only K element
        // left then return the element
        if(list.size() == k) {
            cost += list.stream().reduce(
                         0, Integer::sum);
            return cost;
        } else {
            return -1;
        }
    }
      
    // Function insert the element into
    // the sorted position in the array
    public static void insertInSortedList(
        List<Integer> sortedList, int item) {
        int len = sortedList.size();
        insertInSortedList(sortedList, item, 
                                 0, len - 1);
    }
      
    // Utility function to insert into the
    // array with the help of the position
    public static void insertInSortedList(
        List<Integer> sortedList, int item, 
                       int start, int end) {
        int mid = (int) ((end - start)/ 2.00);
        if(mid == 0 || 
             (mid == sortedList.size() - 1) || 
                sortedList.get(mid) == item) {
            sortedList.add(mid, item);
            return;
        
        else if(sortedList.get(mid) < item) {
            insertInSortedList(sortedList, 
                       item, mid + 1, end);
        } else {
            insertInSortedList(sortedList, 
                     item, start, mid - 1);
        }
    }
      
    // Driver Code
    public static void main(String [] args) {
        List<Integer> stones = new ArrayList<>();
        stones.add(3);
        stones.add(2);
        stones.add(4);
        stones.add(1);
        System.out.println(mergeStones(stones, 3));
        System.out.println(mergeStones(stones, 2));
    }
}
Output:
-1
10

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :