Adding elements of an array until every element becomes greater than or equal to k in C++.

C++Server Side ProgrammingProgramming

Array − An array is a container of elements of the same data type, whose elements are 0 indexed.

In this problem, we will use an array of integers. And check if all the elements are greater than the given number or not. Here we will check if all elements of the array are greater than or equal to a given number k. If not then we will add two minimum elements of the array and treat this sum as a single element. And then again check for the same condition for the new array. If the condition comes out to be true then the number of times the sum is performed is returned.

Array = { 2, 6,3,12, 7} K = 5
Output : 1

Explanation − First we will check if all elements are greater than or k or not. Since they are not we will add two minimum numbers. Which is 2 and 3 so the first element in our new array will be 5. Now, again we will check, this time the condition is fulfilled so we will return no. of additions we have done.


Input − Array and K

Step 1 : check if all elements are greater than or equal to K
Step 2: if(yes){
   Print number of iterations.
Step 3: else {
   Add smallest two elements of the array and make it one element.
Step 4: goto step 1


 Live Demo

using namespace std;
class MinHeap{
   int *harr;
   int capacity;
   int heap_size;
   MinHeap(int *arr, int capacity);
   void heapify(int );
   int parent(int i){
      return (i-1)/2;
   int left(int i){
      return (2*i + 1);
   int right(int i){
      return (2*i + 2);
   int extractMin();
   int getMin(){
      return harr[0];
   int getSize(){
      return heap_size;
   void insertKey(int k);
MinHeap::MinHeap(int arr[], int n){
   heap_size = n;
   capacity = n;
      harr = new int[n];
   for (int i=0; i<n; i++)
      harr[i] = arr[i];
   for (int i=n/2-1; i>=0; i--)
void MinHeap::insertKey(int k){
   int i = heap_size - 1;
   harr[i] = k;
   while (i != 0 && harr[parent(i)] > harr[i]){
      swap(harr[i], harr[parent(i)]);
      i = parent(i);
int MinHeap::extractMin(){
   if (heap_size <= 0)
      return INT_MAX;
   if (heap_size == 1){
      return harr[0];
   int root = harr[0];
   harr[0] = harr[heap_size-1];
   return root;
void MinHeap::heapify(int i){
   int l = left(i);
   int r = right(i);
   int smallest = i;
   if (l < heap_size && harr[l] < harr[i])
      smallest = l;
   if (r < heap_size && harr[r] < harr[smallest])
      smallest = r;
   if (smallest != i){
      swap(harr[i], harr[smallest]);
int main(){
   int arr[] = { 2, 6,3,12, 7};
   int n = sizeof(arr)/sizeof(arr[0]);
   int k = 5;
   MinHeap h(arr, n);
   long int res = 0;
   while (h.getMin() < k){
      if (h.getSize() == 1)
         return -1;
      int first = h.extractMin();
      int second = h.extractMin();
      h.insertKey(first + second);
   cout << res;
   return 0;


Updated on 19-Sep-2019 08:32:43