Open In App

Minimize insertions to make sum of every pair of consecutive array elements at most K

Last Updated : 22 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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 print "-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)



Similar Reads

Minimize insertions required to make ratio of maximum and minimum of all pairs of adjacent array elements at most K
Given an array arr[] and an integer K ( &gt; 1), the task is to find the minimum number of insertions required such that the ratio of the maximum and minimum of all pairs of adjacent elements in the array reduces to at most K. Examples: Input : arr[] = { 2, 10, 25, 21 }, K = 2Output: 3Explanation: Following insertions makes the array satisfy the re
5 min read
Minimize insertions in Array to make ratio of each pair as K
Given an array arr[] of length N the task is to find the minimum number of elements to be added in the array such that there exists every independent pair in the array whose ratio is K. Examples: Input: arr[] = {1, 2, 2, 2, 4, 7}, K = 2Output: 2Explanation: 4, 14 can be added to make the array as {1, 2, 2, 2, 4, 7, 4, 14}Therefore if we make indepe
15 min read
Minimize cost of insertions and deletions required to make all array elements equal
Given a sorted array arr[] of size N (1 ? N ? 105) and two integers A and B, the task is to calculate the minimum cost required to make all array elements equal by increments or decrements. The cost of each increment and decrement are A and B respectively. Examples: Input: arr[] = { 2, 5, 6, 9, 10, 12, 15 }, A = 1, B = 2 Output: 32 Explanation: Inc
11 min read
Minimize the maximum difference of adjacent elements after at most K insertions
Given an array of N elements, the task is to minimize the maximum difference of adjacent elements by inserting at most K elements in the array.Examples: Input: arr = [2, 6, 8] K = 1 Output: 2 Explanation: After insertion of 4 in between 2 and 6, the array becomes [2, 4, 6, 8]. In this case the maximum difference between any adjacent element is 2, w
7 min read
Modify array to a permutation of consecutive numbers of longest length by at most K insertions
Given an array arr[] of length N and an integer K, the task is to find the maximize the length of the array by appending at most K elements such that the array becomes a permutation of consecutive numbers starting from 1. Once K elements are added, sum of two or more array elements can be inserted. Note: Elements can be formed as sum of the element
6 min read
Minimize insertions and deletions in given array A[] to make it identical to array B[]
Given two arrays A[] and B[] of length N and M respectively, the task is to find the minimum number of insertions and deletions on the array A[], required to make both the arrays identical.Note: Array B[] is sorted and all its elements are distinct, operations can be performed at any index not necessarily at the end. Example: Input: A[] = {1, 2, 5,
16 min read
Minimum array insertions required to make consecutive difference &lt;= K
Given an integer array H which represents heights of buildings and an integer K. The task is to reach the last building from the first with the following rules: Getting to a building of height Hj from a building of height Hi is only possible if |Hi - Hj| &lt;= K and the building appears one after another in the array.If getting to a building is not
5 min read
Minimize insertions or deletions to make frequency of each array element equal to its value
Given an array arr[] of N integers, the task is to find the minimum insertion or deletion operations required to make the frequency of each element equal to its value. Example: Input: arr = {3, 2, 3, 1, 2}Output: 1Explanation: Initially, the frequency of integers in the array is freq[3] = 2, freq[2] = 2 and freq[1] = 1. In the 1st operation, insert
6 min read
Minimize replacements to make every element in an array exceed every element in another given array
Given two arrays A[] and B[] of size N and M respectively, where each element is in the range [0, 9], the task is to make each element of the array A[] strictly greater than or smaller than every element in the array B[] by changing any element from either array to any number in the range [0, 9], minimum number of times. Examples: Input: A[] = [0,
10 min read
Rearrange an array to minimize sum of product of consecutive pair elements
We are given an array of even size, we have to sort the array in such a way that the sum of product of alternate elements is minimum also we have to find that minimum sum. Examples: Input : arr[] = {9, 2, 8, 4, 5, 7, 6, 0} Output : Minimum sum of the product of consecutive pair elements: 74 Sorted arr[] for minimum sum: {9, 0, 8, 2, 7, 4, 6, 5} Exp
7 min read
Practice Tags :