Open In App

Minimum increments or decrements by 1 required to make all array elements in AP

Given an array arr[] consisting of N integers, the task is to find the minimum number of increment/decrement by 1 required to be performed on array elements to make all the elements of the given array arr[] in AP. If it is not possible to make the array in AP, then print “-1”.

Examples:



Input: arr[] = {19, 16, 9, 5, 0}
Output: 3
Explanation:
Following are the order of increment/decrements of array elements is made:

  1. Increment array element arr[0](= 19) by 1.
  2. Decrement array element arr[1](= 16) by 1.
  3. Increment array element arr[2](= 9) by 1.

After the above operations, the array arr[] modifies to {20, 15, 10, 5, 0}, which is in AP with first term 20 and common difference -5. Therefore, the total count of element is 3.



Input: arr[] = {1, 2, 3, 4, 10}
Output: -1

Approach: The given problem can be solved by finding the first term and the common difference from the first two elements and then check if all elements can be changed to the AP sequence with the given first term and common difference by simply iterating over the array. Follow the steps below to solve the problem: 

Below is the implementation of the above approach:




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum number
// of elements to be changed to convert
// the array into an AP
int findMinimumMoves(int N, int arr[])
{
    // If N is less than 3
    if (N <= 2) {
        return 0;
    }
 
    // Stores the answer
    int res = N + 1;
 
    // Iterate in the range [-1, 1]
    for (int a = -1; a <= 1; a++) {
 
        // Iterate in the range [-1, 1]
        for (int b = -1; b <= 1; b++) {
 
            // Stores the total changes
            int changes = 0;
 
            if (a != 0) {
                changes++;
            }
 
            if (b != 0) {
                changes++;
            }
 
            // Stores the first element
            // of the AP
            int orig = (arr[0] + a);
 
            // Stores the common difference
            // of the AP
            int diff = (arr[1] + b) - (arr[0] + a);
 
            // Stores whether it is
            // possible to convert the
            // array into AP
            bool good = true;
 
            // Iterate in the range [2, N-1]
            for (int i = 2; i < N; i++) {
 
                // Stores the ith element
                // of the AP
                int actual = orig + i * diff;
 
                // If abs(actual-arr[i])
                // is greater than 1
                if (abs(actual - arr[i]) > 1) {
 
                    // Mark as false
                    good = false;
                    break;
                }
                // If actual is not
                // equal to arr[i]
                if (actual != arr[i])
                    changes++;
            }
            if (!good)
                continue;
 
            // Update the value of res
            res = min(res, changes);
        }
    }
 
    // If res is greater than N
    if (res > N)
        res = -1;
 
    // Return the value of res
    return res;
}
 
// Driver Code
int main()
{
    int arr[] = { 19, 16, 9, 5, 0 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << findMinimumMoves(N, arr);
 
    return 0;
}




// Java program for the above approach
import java.io.*;
 
class GFG{
     
// Function to find the minimum number
// of elements to be changed to convert
// the array into an AP
static int findMinimumMoves(int N, int arr[])
{
     
    // If N is less than 3
    if (N <= 2)
    {
        return 0;
    }
 
    // Stores the answer
    int res = N + 1;
 
    // Iterate in the range [-1, 1]
    for(int a = -1; a <= 1; a++)
    {
         
        // Iterate in the range [-1, 1]
        for(int b = -1; b <= 1; b++)
        {
             
            // Stores the total changes
            int changes = 0;
 
            if (a != 0)
            {
                changes++;
            }
 
            if (b != 0)
            {
                changes++;
            }
 
            // Stores the first element
            // of the AP
            int orig = (arr[0] + a);
 
            // Stores the common difference
            // of the AP
            int diff = (arr[1] + b) - (arr[0] + a);
 
            // Stores whether it is
            // possible to convert the
            // array into AP
            boolean good = true;
 
            // Iterate in the range [2, N-1]
            for(int i = 2; i < N; i++)
            {
                 
                // Stores the ith element
                // of the AP
                int actual = orig + i * diff;
 
                // If abs(actual-arr[i])
                // is greater than 1
                if (Math.abs(actual - arr[i]) > 1)
                {
                     
                    // Mark as false
                    good = false;
                    break;
                }
                 
                // If actual is not
                // equal to arr[i]
                if (actual != arr[i])
                    changes++;
            }
            if (!good)
                continue;
 
            // Update the value of res
            res = Math.min(res, changes);
        }
    }
 
    // If res is greater than N
    if (res > N)
        res = -1;
 
    // Return the value of res
    return res;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 19, 16, 9, 5, 0 };
    int N = arr.length;
 
    System.out.println(findMinimumMoves(N, arr));
}
}
 
// This code is contributed by Potta Lokesh




# Python3 program for the above approach
 
# Function to find the minimum number
# of elements to be changed to convert
# the array into an AP
def findMinimumMoves(N, arr):
     
    # If N is less than 3
    if (N <= 2):
        return 0
 
    # Stores the answer
    res = N + 1
 
    # Iterate in the range [-1, 1]
    for a in range(-1, 2, 1):
 
        # Iterate in the range [-1, 1]
        for b in range(-1, 2, 1):
             
            # Stores the total changes
            changes = 0
 
            if (a != 0):
                changes += 1
 
            if (b != 0):
                changes += 1
 
            # Stores the first element
            # of the AP
            orig = (arr[0] + a)
 
            # Stores the common difference
            # of the AP
            diff = (arr[1] + b) - (arr[0] + a)
 
            # Stores whether it is
            # possible to convert the
            # array into AP
            good = True
 
            # Iterate in the range [2, N-1]
            for i in range(2, N, 1):
                 
                # Stores the ith element
                # of the AP
                actual = orig + i * diff
 
                # If abs(actual-arr[i])
                # is greater than 1
                if (abs(actual - arr[i]) > 1):
 
                    # Mark as false
                    good = False
                    break
 
                # If actual is not
                # equal to arr[i]
                if (actual != arr[i]):
                    changes += 1
 
            if (good == False):
                continue
 
            # Update the value of res
            res = min(res, changes)
 
    # If res is greater than N
    if (res > N):
        res = -1
 
    # Return the value of res
    return res
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 19, 16, 9, 5, 0 ]
    N = len(arr)
     
    print(findMinimumMoves(N, arr))
 
# This code is contributed by ipg2016107




// C# program for the above approach
using System;
 
class GFG{
     
// Function to find the minimum number
// of elements to be changed to convert
// the array into an AP
static int findMinimumMoves(int N, int[] arr)
{
     
    // If N is less than 3
    if (N <= 2)
    {
        return 0;
    }
 
    // Stores the answer
    int res = N + 1;
 
    // Iterate in the range [-1, 1]
    for(int a = -1; a <= 1; a++)
    {
         
        // Iterate in the range [-1, 1]
        for(int b = -1; b <= 1; b++)
        {
             
            // Stores the total changes
            int changes = 0;
 
            if (a != 0)
            {
                changes++;
            }
 
            if (b != 0)
            {
                changes++;
            }
 
            // Stores the first element
            // of the AP
            int orig = (arr[0] + a);
 
            // Stores the common difference
            // of the AP
            int diff = (arr[1] + b) - (arr[0] + a);
 
            // Stores whether it is
            // possible to convert the
            // array into AP
            bool good = true;
 
            // Iterate in the range [2, N-1]
            for(int i = 2; i < N; i++)
            {
                 
                // Stores the ith element
                // of the AP
                int actual = orig + i * diff;
 
                // If abs(actual-arr[i])
                // is greater than 1
                if (Math.Abs(actual - arr[i]) > 1)
                {
                     
                    // Mark as false
                    good = false;
                    break;
                }
                 
                // If actual is not
                // equal to arr[i]
                if (actual != arr[i])
                    changes++;
            }
            if (!good)
                continue;
 
            // Update the value of res
            res = Math.Min(res, changes);
        }
    }
 
    // If res is greater than N
    if (res > N)
        res = -1;
 
    // Return the value of res
    return res;
}
 
 
// Driver code
static public void Main()
{
    int[] arr = { 19, 16, 9, 5, 0 };
    int N = arr.Length;
 
    Console.WriteLine(findMinimumMoves(N, arr));
}
}
 
// This code is contributed by target_2.




<script>
 
// Javascript program for the above approach
 
// Function to find the minimum number
// of elements to be changed to convert
// the array into an AP
function findMinimumMoves(N, arr)
{
     
    // If N is less than 3
    if (N <= 2)
    {
        return 0;
    }
 
    // Stores the answer
    let res = N + 1;
 
    // Iterate in the range [-1, 1]
    for(let a = -1; a <= 1; a++)
    {
         
        // Iterate in the range [-1, 1]
        for(let b = -1; b <= 1; b++)
        {
             
            // Stores the total changes
            let changes = 0;
 
            if (a != 0)
            {
                changes++;
            }
 
            if (b != 0)
            {
                changes++;
            }
 
            // Stores the first element
            // of the AP
            let orig = (arr[0] + a);
 
            // Stores the common difference
            // of the AP
            let diff = (arr[1] + b) - (arr[0] + a);
 
            // Stores whether it is
            // possible to convert the
            // array into AP
            let good = true;
 
            // Iterate in the range [2, N-1]
            for(let i = 2; i < N; i++)
            {
                 
                // Stores the ith element
                // of the AP
                let actual = orig + i * diff;
 
                // If abs(actual-arr[i])
                // is greater than 1
                if (Math.abs(actual - arr[i]) > 1)
                {
                     
                    // Mark as false
                    good = false;
                    break;
                }
                 
                // If actual is not
                // equal to arr[i]
                if (actual != arr[i])
                    changes++;
            }
            if (!good)
                continue;
 
            // Update the value of res
            res = Math.min(res, changes);
        }
    }
 
    // If res is greater than N
    if (res > N)
        res = -1;
 
    // Return the value of res
    return res;
}
 
// Driver Code
let arr = [ 19, 16, 9, 5, 0 ];
let N = arr.length;
 
document.write(findMinimumMoves(N, arr));
 
// This code is contributed by target_2
     
</script>

Output: 
3

 

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


Article Tags :