Minimum increments to convert to an array of consecutive integers

Given an array arr[] with N elements, the task is to find the minimum number of operations required so that an Arithmetic Progression with the array elements is achieved with common difference as 1. In a single operation, any element can be incremented by 1.

Examples:

Input: arr[] = {4, 4, 5, 5, 7}
Output: 5
Desired array is {4, 5, 6, 7, 8} which
can be achieved in minimum possible operations.



Input: arr[] = {11, 2, 5, 6}
Output: 26
Since we are allowed to do only increment, we
change the array to {11, 12, 13, 14}

Approach:

  • We can utilize Binary Search to solve this problem.
  • We will built the desired array with fixed last element which will be increased if the solution isn’t valid or decreased if its valid just like in binary search.
  • Check that all the elements of desired array are greater than or equal to input array in order to perform operations on the elements to make them equal to the desired elements. Find the count of operations.
  • Find the minimum possible value of last element which satisfy the condition of all the elements in the desired array.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
// Function that return true if the
// required array can be generated
// with m as the last element
bool check(int m, int n, int arr[])
{
    // Build the desired array
    int desired[n];
    for (int i = n - 1; i >= 0; i--) {
        desired[i] = m;
        m--;
    }
  
    // Check if the given array can
    // be converted to the desired array
    // with the given operation
    for (int i = 0; i < n; i++) {
        if (arr[i] > desired[i] || desired[i] < 1) {
            return false;
        }
    }
  
    return true;
}
  
// Function to return the minimum number
// of operations required to convert the
// given array to an increasing AP series
// with common difference as 1
int minOperations(int arr[], int n)
{
    int start = (int)arr[n - 1];
    int end = *(max_element(arr, arr + n)) + n;
    int max_arr = 0;
  
    // Apply Binary Search
    while (start <= end) {
        int mid = (start + end) / 2;
  
        // If array can be generated with
        // mid as the last element
        if (check(mid, n, arr)) {
  
            // Current ans is mid
            max_arr = mid;
  
            // Check whether the same can be
            // achieved with even less operations
            end = mid - 1;
        }
        else {
            start = mid + 1;
        }
    }
  
    // Build the desired array
    int desired[n];
    for (int i = n - 1; i >= 0; i--) {
        desired[i] = max_arr;
        max_arr--;
    }
  
    // Calculate the number of
    // operations required
    int operations = 0;
    for (int i = 0; i < n; i++) {
        operations += (desired[i] - arr[i]);
    }
  
    // Return the number of
    // operations required
    return operations;
}
  
// Driver code
int main()
{
    int arr[] = { 4, 4, 5, 5, 7 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    cout << minOperations(arr, n);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
import java.util.Arrays;
  
class GFG 
{
  
    // Function that return true if the
    // required array can be generated
    // with m as the last element
    static boolean check(int m, int n, int arr[]) 
    {
        // Build the desired array
        int[] desired = new int[n];
        for (int i = n - 1; i >= 0; i--) 
        {
            desired[i] = m;
            m--;
        }
  
        // Check if the given array can
        // be converted to the desired array
        // with the given operation
        for (int i = 0; i < n; i++)
        {
            if (arr[i] > desired[i] || desired[i] < 1
            {
                return false;
            }
        }
  
        return true;
    }
  
    // Function to return the minimum number
    // of operations required to convert the
    // given array to an increasing AP series
    // with common difference as 1
    static int minOperations(int arr[], int n)
    {
        int start = (int) arr[n - 1];
        int end = Arrays.stream(arr).max().getAsInt() + n;
        int max_arr = 0;
  
        // Apply Binary Search
        while (start <= end) 
        {
            int mid = (start + end) / 2;
  
            // If array can be generated with
            // mid as the last element
            if (check(mid, n, arr))
            {
  
                // Current ans is mid
                max_arr = mid;
  
                // Check whether the same can be
                // achieved with even less operations
                end = mid - 1;
            
            else
            {
                start = mid + 1;
            }
        }
  
        // Build the desired array
        int[] desired = new int[n];
        for (int i = n - 1; i >= 0; i--) 
        {
            desired[i] = max_arr;
            max_arr--;
        }
  
        // Calculate the number of
        // operations required
        int operations = 0;
        for (int i = 0; i < n; i++) 
        {
            operations += (desired[i] - arr[i]);
        }
  
        // Return the number of
        // operations required
        return operations;
    }
  
    // Driver code
    public static void main(String[] args) 
    {
        int arr[] = {4, 4, 5, 5, 7};
        int n = arr.length;
  
        System.out.println(minOperations(arr, n));
    }
}
  
// This code is contributed by Princi Singh

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the approach 
  
# Function that return true if the 
# required array can be generated 
# with m as the last element 
def check( m, n, arr) :
  
    # Build the desired array 
    desired = [0]*n; 
    for i in range(n-1,-1,-1) :
        desired[i] = m; 
        m -= 1
      
  
    # Check if the given array can 
    # be converted to the desired array 
    # with the given operation 
    for i in range(n) : 
        if (arr[i] > desired[i] or desired[i] < 1) : 
            return False
  
    return True
  
  
# Function to return the minimum number 
# of operations required to convert the 
# given array to an increasing AP series 
# with common difference as 1 
def minOperations(arr, n) : 
  
    start = arr[n - 1]; 
    end = max(arr) + n; 
    max_arr = 0
  
    # Apply Binary Search 
    while (start <= end) : 
        mid = (start + end) // 2
  
        # If array can be generated with 
        # mid as the last element 
        if (check(mid, n, arr)) :
  
            # Current ans is mid 
            max_arr = mid; 
  
            # Check whether the same can be 
            # achieved with even less operations 
            end = mid - 1
          
        else :
            start = mid + 1
  
    # Build the desired array 
    desired = [0]* n; 
    for i in range(n-1, -1,-1) :
        desired[i] = max_arr; 
        max_arr -= 1
      
  
    # Calculate the number of 
    # operations required 
    operations = 0
    for i in range(n) :
        operations += (desired[i] - arr[i]); 
      
    # Return the number of 
    # operations required 
    return operations; 
  
  
# Driver code 
if __name__ == "__main__"
  
    arr = [ 4, 4, 5, 5, 7 ]; 
    n = len(arr); 
  
    print(minOperations(arr, n)); 
      
    # This code is contributed by AnkitRai01

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the approach
using System;     
using System.Linq; 
  
class GFG 
{
  
    // Function that return true if the
    // required array can be generated
    // with m as the last element
    static Boolean check(int m, int n, int []arr) 
    {
        // Build the desired array
        int[] desired = new int[n];
        for (int i = n - 1; i >= 0; i--) 
        {
            desired[i] = m;
            m--;
        }
  
        // Check if the given array can
        // be converted to the desired array
        // with the given operation
        for (int i = 0; i < n; i++)
        {
            if (arr[i] > desired[i] || desired[i] < 1) 
            {
                return false;
            }
        }
  
        return true;
    }
  
    // Function to return the minimum number
    // of operations required to convert the
    // given array to an increasing AP series
    // with common difference as 1
    static int minOperations(int []arr, int n)
    {
        int start = (int) arr[n - 1];
        int end = arr.Max() + n;
        int max_arr = 0;
  
        // Apply Binary Search
        while (start <= end) 
        {
            int mid = (start + end) / 2;
  
            // If array can be generated with
            // mid as the last element
            if (check(mid, n, arr))
            {
  
                // Current ans is mid
                max_arr = mid;
  
                // Check whether the same can be
                // achieved with even less operations
                end = mid - 1;
            
            else
            {
                start = mid + 1;
            }
        }
  
        // Build the desired array
        int[] desired = new int[n];
        for (int i = n - 1; i >= 0; i--) 
        {
            desired[i] = max_arr;
            max_arr--;
        }
  
        // Calculate the number of
        // operations required
        int operations = 0;
        for (int i = 0; i < n; i++) 
        {
            operations += (desired[i] - arr[i]);
        }
  
        // Return the number of
        // operations required
        return operations;
    }
  
    // Driver code
    public static void Main(String[] args) 
    {
        int []arr = {4, 4, 5, 5, 7};
        int n = arr.Length;
  
        Console.WriteLine(minOperations(arr, n));
    }
}
  
// This code contributed by Rajput-Ji

chevron_right


Output:

5


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.