# Minimize cost of insertions and deletions required to make all array elements equal

• Last Updated : 30 Sep, 2022

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:
Increment arr[0] by 8, arr[1] by 5, arr[2] by 4, arr[3] by 1, arr[4] by 0. Decrement arr[5] by 2, arr[6] by 5.
Therefore, arr[] modifies to { 10, 10, 10, 10, 10, 10, 10 }.
Therefore, total cost required = (8 + 5 + 4 + 1 + 0) * 1 + (2 + 5) * 2 = 18 + 14 = 32

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

Approach: Follow the steps below the implementation:

Below is the implementation of the above approach.

## C++

 `// C++ program to implement``// the above approach` `#include ``using` `namespace` `std;` `// Function to find minimum cost``// required to make all array elements equal``long` `long` `minCost(``int` `arr[], ``int` `A,``                  ``int` `B, ``int` `N)``{` `    ``// Sort the array``    ``sort(arr, arr + N);` `    ``// Stores the prefix sum and sum``    ``// of the array respectively``    ``long` `long` `cumarr[N], sum = 0;` `    ``// Traverse the array``    ``for` `(``int` `i = 0; i < N; i++) {` `        ``// Update sum``        ``sum += arr[i];` `        ``// Update prefix sum``        ``cumarr[i] = sum;``    ``}` `    ``// Update middle element``    ``int` `mid = (N - 1) / 2;` `    ``// Calculate cost to convert``    ``// every element to mid element``    ``long` `long` `ans``        ``= (arr[mid] * (mid + 1)``           ``- cumarr[mid])``              ``* A``          ``+ (cumarr[N - 1] - cumarr[mid]``             ``- (arr[mid] * (N - 1 - mid)))``                ``* B;` `    ``if` `(A == B)``        ``return` `ans;` `    ``else` `if` `(A < B) {``        ``int` `low = mid, high = N - 1;` `        ``// Binary search``        ``while` `(low <= high) {` `            ``mid = low + (high - low) / 2;` `            ``long` `long` `curr``                ``= (arr[mid] * (mid + 1)``                   ``- cumarr[mid])``                      ``* A``                  ``+ (cumarr[N - 1] - cumarr[mid]``                     ``- (arr[mid] * (N - 1 - mid)))``                        ``* B;` `            ``if` `(curr <= ans) {``                ``ans = curr;``                ``low = mid + 1;``            ``}``            ``else``                ``high = mid - 1;``        ``}` `        ``return` `ans;``    ``}` `    ``else` `{``        ``int` `low = 0, high = mid;` `        ``// Binary search``        ``while` `(low <= high) {``            ``mid = low + (high - low) / 2;``            ``long` `long` `curr``                ``= (arr[mid] * (mid + 1)``                   ``- cumarr[mid])``                      ``* A``                  ``+ (cumarr[N - 1] - cumarr[mid]``                     ``- (arr[mid] * (N - 1 - mid)))``                        ``* B;` `            ``if` `(curr <= ans) {``                ``ans = curr;``                ``high = mid - 1;``            ``}``            ``else``                ``low = mid + 1;``        ``}` `        ``return` `ans;``    ``}``}` `// Driver Code``int` `main()``{``    ``int` `arr[] = { 2, 5, 6, 9, 10, 12, 15 };``    ``int` `A = 1, B = 2;``    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr[0]);``    ``cout << minCost(arr, A, B, N);` `    ``return` `0;``}`

## Java

 `// Java program to implement``// the above approach``import` `java.io.*;``import` `java.util.*;` `class` `GFG{` `// Function to find minimum cost required``// to make all array elements equal``static` `int` `minCost(``int``[] arr, ``int` `A,``                   ``int` `B, ``int` `N)``{``    ` `    ``// Sort the array``    ``Arrays.sort(arr);` `    ``// Stores the prefix sum and sum``    ``// of the array respectively``    ``int``[] cumarr = ``new` `int``[N];``    ``int` `sum = ``0``;` `    ``// Traverse the array``    ``for``(``int` `i = ``0``; i < N; i++)``    ``{``        ` `        ``// Update sum``        ``sum += arr[i];` `        ``// Update prefix sum``        ``cumarr[i] = sum;``    ``}` `    ``// Update middle element``    ``int` `mid = (N - ``1``) / ``2``;` `    ``// Calculate cost to convert``    ``// every element to mid element``    ``int` `ans = (arr[mid] * (mid + ``1``) - cumarr[mid]) *``                      ``A + (cumarr[N - ``1``] -``            ``cumarr[mid] - (arr[mid] * (N -``                      ``1` `- mid))) * B;``              ` `    ``if` `(A == B)``        ``return` `ans;``        ` `    ``else` `if` `(A < B)``    ``{``        ``int` `low = mid, high = N - ``1``;``        ` `        ``// Binary search``        ``while` `(low <= high)``        ``{``            ``mid = low + (high - low) / ``2``;` `            ``int` `curr = (arr[mid] * (mid + ``1``) -``                    ``cumarr[mid]) * A + (cumarr[N - ``1``] -``                     ``cumarr[mid] - (arr[mid] *``                              ``(N - ``1` `- mid))) * B;` `            ``if` `(curr <= ans)``            ``{``                ``ans = curr;``                ``low = mid + ``1``;``            ``}``            ``else``                ``high = mid - ``1``;``        ``}``        ``return` `ans;``    ``}` `    ``else``    ``{``        ``int` `low = ``0``, high = mid;` `        ``// Binary search``        ``while` `(low <= high)``        ``{``            ``mid = low + (high - low) / ``2``;``            ``int` `curr = (arr[mid] * (mid + ``1``) -``                    ``cumarr[mid]) * A + (cumarr[N - ``1``] -``                     ``cumarr[mid] - (arr[mid] * (N - ``1` `-``                          ``mid))) * B;` `            ``if` `(curr <= ans)``            ``{``                ``ans = curr;``                ``high = mid - ``1``;``            ``}``            ``else``                ``low = mid + ``1``;``        ``}``        ``return` `ans;``    ``}``}` `// Driver Code``public` `static` `void` `main(String[] args)``{``    ``int``[] arr = { ``2``, ``5``, ``6``, ``9``, ``10``, ``12``, ``15` `};``    ``int` `A = ``1``, B = ``2``;``    ``int` `N = (``int``)(arr.length);``    ` `    ``System.out.println(minCost(arr, A, B, N));``}``}` `// This code is contributed by susmitakundugoaldanga`

## Python3

 `# Python program to implement``# the above approach` `# Function to find minimum cost required``# to make all array elements equal``def` `minCost(arr, A, B, N):``  ` `    ``# Sort the array``    ``arr.sort();` `    ``# Stores the prefix sum and sum``    ``# of the array respectively``    ``cumarr ``=` `[``0``]``*``N;``    ``sum` `=` `0``;` `    ``# Traverse the array``    ``for` `i ``in` `range``(N):``      ` `        ``# Update sum``        ``sum` `+``=` `arr[i];` `        ``# Update prefix sum``        ``cumarr[i] ``=` `sum``;` `    ``# Update middle element``    ``mid ``=` `(N ``-` `1``) ``/``/` `2``;` `    ``# Calculate cost to convert``    ``# every element to mid element``    ``ans ``=` `(arr[mid] ``*` `(mid ``+` `1``) ``-` `cumarr[mid]) ``*` `A\``    ``+` `(cumarr[N ``-` `1``] ``-` `cumarr[mid] ``-` `(arr[mid] ``*` `(N ``-` `1` `-` `mid))) ``*` `B;``    ``if` `(A ``=``=` `B):``        ``return` `ans;``    ``elif` `(A < B):``        ``low ``=` `mid; high ``=` `N ``-` `1``;` `        ``# Binary search``        ``while` `(low <``=` `high):``            ``mid ``=` `low ``+` `(high ``-` `low) ``/``/` `2``;``            ``curr ``=` `(arr[mid] ``*` `(mid ``+` `1``) ``-` `cumarr[mid]) ``*` `A\``            ``+` `(cumarr[N ``-` `1``] ``-` `cumarr[mid] ``-` `(arr[mid] ``*` `(N ``-` `1` `-` `mid))) ``*` `B;``            ``if` `(curr <``=` `ans):``                ``ans ``=` `curr;``                ``low ``=` `mid ``+` `1``;``            ``else``:``                ``high ``=` `mid ``-` `1``;``        ``return` `ans;``    ``else``:``        ``low ``=` `0``;``        ``high ``=` `mid;` `        ``# Binary search``        ``while` `(low <``=` `high):``            ``mid ``=` `low ``+` `(high ``-` `low) ``/``/` `2``;``            ``curr ``=` `(arr[mid] ``*` `(mid ``+` `1``) ``-` `cumarr[mid]) ``*` `A\``            ``+` `(cumarr[N ``-` `1``] ``-` `cumarr[mid] ``-` `(arr[mid] ``*` `(N ``-` `1` `-` `mid))) ``*` `B;``            ``if` `(curr <``=` `ans):``                ``ans ``=` `curr;``                ``high ``=` `mid ``-` `1``;``            ``else``:``                ``low ``=` `mid ``+` `1``;``        ``return` `ans;` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ``arr ``=` `[``2``, ``5``, ``6``, ``9``, ``10``, ``12``, ``15``];``    ``A ``=` `1``; B ``=` `2``;``    ``N ``=` `(``int``)(``len``(arr));` `    ``print``(minCost(arr, A, B, N));``    ` `    ``# This code is contributed by 29AjayKumar`

## C#

 `// C# program to implement``// the above approach``using` `System;``using` `System.Collections.Generic;``class` `GFG``{` `    ``// Function to find minimum cost``    ``// required to make all array elements equal``    ``static` `ulong` `minCost(``ulong``[] arr, ``ulong` `A, ``ulong` `B,``                         ``ulong` `N)``    ``{` `        ``// Sort the array``        ``Array.Sort(arr);` `        ``// Stores the prefix sum and sum``        ``// of the array respectively``        ``ulong``[] cumarr = ``new` `ulong``[N];``        ``ulong` `sum = 0;` `        ``// Traverse the array``        ``for` `(``ulong` `i = 0; i < N; i++)``        ``{` `            ``// Update sum``            ``sum += arr[i];` `            ``// Update prefix sum``            ``cumarr[i] = sum;``        ``}` `        ``// Update middle element``        ``ulong` `mid = (N - 1) / 2;` `        ``// Calculate cost to convert``        ``// every element to mid element``        ``ulong` `ans = (arr[mid] * (mid + 1) - cumarr[mid]) * A``                    ``+ (cumarr[N - 1] - cumarr[mid]``                       ``- (arr[mid] * (N - 1 - mid)))``                          ``* B;``        ``if` `(A == B)``            ``return` `ans;``        ``else` `if` `(A < B) {``            ``ulong` `low = mid, high = N - 1;` `            ``// Binary search``            ``while` `(low <= high) {` `                ``mid = low + (high - low) / 2;` `                ``ulong` `curr``                    ``= (arr[mid] * (mid + 1) - cumarr[mid])``                          ``* A``                      ``+ (cumarr[N - 1] - cumarr[mid]``                         ``- (arr[mid] * (N - 1 - mid)))``                            ``* B;` `                ``if` `(curr <= ans) {``                    ``ans = curr;``                    ``low = mid + 1;``                ``}``                ``else``                    ``high = mid - 1;``            ``}` `            ``return` `ans;``        ``}` `        ``else` `{``            ``ulong` `low = 0, high = mid;` `            ``// Binary search``            ``while` `(low <= high) {``                ``mid = low + (high - low) / 2;``                ``ulong` `curr``                    ``= (arr[mid] * (mid + 1) - cumarr[mid])``                          ``* A``                      ``+ (cumarr[N - 1] - cumarr[mid]``                         ``- (arr[mid] * (N - 1 - mid)))``                            ``* B;` `                ``if` `(curr <= ans) {``                    ``ans = curr;``                    ``high = mid - 1;``                ``}``                ``else``                    ``low = mid + 1;``            ``}``            ``return` `ans;``        ``}``    ``}` `    ``// Driver Code``    ``public` `static` `void` `Main()``    ``{``        ``ulong``[] arr = { 2, 5, 6, 9, 10, 12, 15 };``        ``ulong` `A = 1, B = 2;``        ``ulong` `N = (``ulong``)(arr.Length);``        ``Console.Write(minCost(arr, A, B, N));``    ``}``}` `// This code is contributed by subhammahato348`

## Javascript

 ``

Output:

`32`

Time Complexity: O(N*logN), for sorting the array
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up