Minimum increments to convert to an array of consecutive integers - GeeksforGeeks

14 May, 2021
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++
Java
Python3
C#
Javascript
// 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 elementbool 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 1int 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 codeint main(){    int arr[] = { 4, 4, 5, 5, 7 };    int n = sizeof(arr) / sizeof(arr[0]);     cout << minOperations(arr, n);     return 0;}
// Java implementation of the approachimport 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
# Python3 implementation of the approach # Function that return true if the# required array can be generated# with m as the last elementdef 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 1def 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 codeif __name__ == "__main__" :     arr = [ 4, 4, 5, 5, 7 ];    n = len(arr);     print(minOperations(arr, n));         # This code is contributed by AnkitRai01
// C# implementation of the approachusing 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
<script>  // Javascript implementation of the approach // Function that return true if the// required array can be generated// with m as the last elementfunction check(m, n, arr){    // Build the desired array    var desired = Array(n);    for (var 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 (var 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 1function minOperations(arr, n){    var start = arr[n - 1];    var end = arr.reduce((a,b)=> Math.max(a,b)) + n;    var max_arr = 0;     // Apply Binary Search    while (start <= end) {        var mid = parseInt((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    var desired = Array(n);    for (var i = n - 1; i >= 0; i--) {        desired[i] = max_arr;        max_arr--;    }     // Calculate the number of    // operations required    var operations = 0;    for (var i = 0; i < n; i++) {        operations += (desired[i] - arr[i]);    }     // Return the number of    // operations required    return operations;} // Driver codevar arr = [4, 4, 5, 5, 7 ];var n = arr.length;document.write( minOperations(arr, n)); </script>
5
 
ankthon
princi singh
Rajput-Ji
noob2000
arithmetic progression
Binary Search
Arrays
Searching
Arrays
Searching
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Count pairs with given sum
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Binary Search
Median of two sorted arrays of different sizes
Find the index of an array element in Java
Two Pointers Technique
Count number of occurrences (or frequency) in a sorted array