Skip to content
Related Articles

Related Articles

Minimize insertions to make sum of every pair of consecutive array elements at most K
  • Last Updated : 16 Apr, 2021

Given an array arr[] of N positive integers and an integer K, the task is to find the minimum number of insertions of any positive integers is required such that the sum of every adjacent element is at most K. If it is not possible, then print “-1”.

Examples:

Input: arr[] = {1, 2, 3, 4, 5}, K = 6
Output: 2
Explanation:
Following insertions are required:
Operation 1: Insert 1 between indices 2 and 3. Therefore, the array modifies to {1, 2, 3, 1, 4, 5}.
Operation 2: Insert 1 between index 4 and 5. Therefore, the array modifies to {1, 2, 3, 1, 4, 1, 5}. Therefore, the minimum number of insertions required is 2.

Input: arr[] = {4, 5, 6, 7, 7, 8}, K = 8
Output: -1

Approach: The idea is based on the fact that inserting 1 between the elements whose sum exceeds K makes the sum of consecutive elements less than K if the element itself is not equal to or greater than K. Follow the steps below to solve the given problem:



  • Initialize three variables, say res = 0, possible = 1, and last = 0 to store the count of minimum insertions, to check if it is possible to make the sum of all consecutive pairs at most K or not, and to store the previous number to the current element respectively.
  • Traverse the array arr[] and perform the following steps:
    • If the value of arr[i] is at least K, then it is not possible to make the sum of all consecutive pairs at most K.
    • If the sum of last and arr[i] is greater than K, then increment res by 1 and assign last = arr[i].
  • After completing the above steps, if the value of possible is 1, then print the value of res as the minimum number of insertions required. Otherwise, print “-1”.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to count minimum number of
// insertions required to make sum of
// every pair of adjacent elements at most K
void minimumInsertions(int arr[],
                       int N, int K)
{
    // Stores if it is possible to
    // make sum of each pair of
    // adjacent elements at most K
    bool possible = 1;
 
    // Stores the count of insertions
    int res = 0;
 
    // Stores the previous
    // value to index i
    int last = 0;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // If arr[i] is greater
        // than or equal to K
        if (arr[i] >= K) {
 
            // Mark possible 0
            possible = 0;
            break;
        }
 
        // If last + arr[i]
        // is greater than K
        if (last + arr[i] > K)
 
            // Increment res by 1
            res++;
 
        // Assign arr[i] to last
        last = arr[i];
    }
 
    // If possible to make the sum of
    // pairs of adjacent elements at most K
    if (possible) {
        cout << res;
    }
 
    // Otherwise print "-1"
    else {
 
        cout << "-1";
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5 };
    int K = 6;
    int N = sizeof(arr) / sizeof(arr[0]);
 
    minimumInsertions(arr, N, K);
 
    return 0;
}

Java




// Java program for the above approach
import java.util.*;
class GFG
{
 
  // Function to count minimum number of
  // insertions required to make sum of
  // every pair of adjacent elements at most K
  static void minimumInsertions(int arr[],
                                int N, int K)
  {
 
    // Stores if it is possible to
    // make sum of each pair of
    // adjacent elements at most K
    boolean possible = true;
 
    // Stores the count of insertions
    int res = 0;
 
    // Stores the previous
    // value to index i
    int last = 0;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
      // If arr[i] is greater
      // than or equal to K
      if (arr[i] >= K) {
 
        // Mark possible 0
        possible = false;
        break;
      }
 
      // If last + arr[i]
      // is greater than K
      if (last + arr[i] > K)
 
        // Increment res by 1
        res++;
 
      // Assign arr[i] to last
      last = arr[i];
    }
 
    // If possible to make the sum of
    // pairs of adjacent elements at most K
    if (possible) {
      System.out.print(res);
    }
 
    // Otherwise print "-1"
    else {
 
      System.out.print("-1");
    }
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int arr[] = { 1, 2, 3, 4, 5 };
    int K = 6;
    int N = arr.length;
 
    minimumInsertions(arr, N, K);
 
  }
}
 
// This code is contributed by shikhasingrajput

Python3




# Python 3 program for the above approach
 
# Function to count minimum number of
# insertions required to make sum of
# every pair of adjacent elements at most K
def minimumInsertions(arr, N, K):
 
    # Stores if it is possible to
    # make sum of each pair of
    # adjacent elements at most K
    possible = 1
 
    # Stores the count of insertions
    res = 0
 
    # Stores the previous
    # value to index i
    last = 0
 
    # Traverse the array
    for i in range(N):
 
        # If arr[i] is greater
        # than or equal to K
        if (arr[i] >= K):
 
            # Mark possible 0
            possible = 0
            break
 
        # If last + arr[i]
        # is greater than K
        if (last + arr[i] > K):
 
            # Increment res by 1
            res += 1
 
        # Assign arr[i] to last
        last = arr[i]
 
    # If possible to make the sum of
    # pairs of adjacent elements at most K
    if (possible):
        print(res)
 
    # Otherwise print "-1"
    else:
        print("-1")
 
# Driver Code
if __name__ == "__main__":
 
    arr = [1, 2, 3, 4, 5]
    K = 6
    N = len(arr)
 
    minimumInsertions(arr, N, K)
 
    # This code is contributed by ukasp.

C#




// C# program for the above approach
using System;
 
class GFG{
 
  // Function to count minimum number of
  // insertions required to make sum of
  // every pair of adjacent elements at most K
  static void minimumInsertions(int[] arr,
                                int N, int K)
  {
 
    // Stores if it is possible to
    // make sum of each pair of
    // adjacent elements at most K
    bool possible = true;
 
    // Stores the count of insertions
    int res = 0;
 
    // Stores the previous
    // value to index i
    int last = 0;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
      // If arr[i] is greater
      // than or equal to K
      if (arr[i] >= K) {
 
        // Mark possible 0
        possible = false;
        break;
      }
 
      // If last + arr[i]
      // is greater than K
      if (last + arr[i] > K)
 
        // Increment res by 1
        res++;
 
      // Assign arr[i] to last
      last = arr[i];
    }
 
    // If possible to make the sum of
    // pairs of adjacent elements at most K
    if (possible) {
      Console.Write(res);
    }
 
    // Otherwise print "-1"
    else {
 
      Console.Write("-1");
    }
  }
 
  // Driver code
  static void Main()
  {
 
    int[] arr = { 1, 2, 3, 4, 5 };
    int K = 6;
    int N = arr.Length;
 
    minimumInsertions(arr, N, K);
  }
}
 
// This code is contributed by sanjoy_62.

Javascript




<script>
 
// Javascript program for the above approach
 
    // Function to count minimum number of
    // insertions required to make sum of
    // every pair of adjacent elements at most K
    function minimumInsertions(arr , N , K) {
 
        // Stores if it is possible to
        // make sum of each pair of
        // adjacent elements at most K
        var possible = true;
 
        // Stores the count of insertions
        var res = 0;
 
        // Stores the previous
        // value to index i
        var last = 0;
 
        // Traverse the array
        for (i = 0; i < N; i++) {
 
            // If arr[i] is greater
            // than or equal to K
            if (arr[i] >= K) {
 
                // Mark possible 0
                possible = false;
                break;
            }
 
            // If last + arr[i]
            // is greater than K
            if (last + arr[i] > K)
 
                // Increment res by 1
                res++;
 
            // Assign arr[i] to last
            last = arr[i];
        }
 
        // If possible to make the sum of
        // pairs of adjacent elements at most K
        if (possible) {
            document.write(res);
        }
 
        // Otherwise prvar "-1"
        else {
 
            document.write("-1");
        }
    }
 
    // Driver Code
     
        var arr = [ 1, 2, 3, 4, 5 ];
        var K = 6;
        var N = arr.length;
 
        minimumInsertions(arr, N, K);
 
 
// This code contributed by umadevi9616
 
</script>
Output: 
2

 

Time Complexity: O(N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :