Open In App

Equalizing array using increment under modulo 3

Last Updated : 14 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array A containing N non-negative integers. Only following operation can be performed on the array: 
A[i] = ( A[i] + 1 ) % 3 
where A[i] is the element of array A at index i, and performing this operation once costs 1 unit. Find the minimum cost to make all elements equal.

Examples :  

Input : 1 0 3 2
Output : 4 units
Explanation: First 3 is converted to 1(3 + 1 % 3 = 1). 
Then, if we try to make all elements equal to 1, then
converting 0 to 1 will cost "1" and 2 to 1 will cost "2". 
Therefore, in total cost=3 + 1(to convert 3 to 1) = 4, 
which is minimum.  

Input : 98 4 3 1
Output : 6 units
Explanation: 98, 4 and 3 are converted to 0, 2 and 1.
So, now array becomes {0, 2, 1, 1}. If we try to convert
every element in our new array equal to 1, then converting
0 to 1 will cost "1" and 2 to 1 will cost "2". So, total
cost= 3+ 3(conversion of 98, 4 and 3) = 6, which is the minimum cost.

Approach: At first, we will try to convert all the numbers greater than 2 to a number between 0 to 2.Since, numbers from 0 to 2 will not exceed 2 using the only allowed operation A(i)=(A(i)+1) % 3(No matter how many times we do this operation). Then we will fix one of the 3 possible values(0 to 2) and find the cost of making all elements equal to it. 

Minimum cost out of the three + the extra cost to convert all numbers greater than 2 to a number between 0 to 2 will be our answer. One special case we need look here is, if all the elements are equal by default (like in array {7, 7, 7, 7}), then our answer will be zero.

Implementation:

C++




// CPP program to find minimum cost to
// equalize an array with increment under
// modulo 3 operation.
#include <bits/stdc++.h>
using namespace std;
 
int mincost(int a[], int n)
{
    int c = 1;
     
    // loop to check whether all
    // elements are equal or not
    for (int i = 0; i < n; i++)
        if (a[i] == a[i + 1])
            c++;
     
    // A special case when all
    // elements are equal
    if (c == n)
        return 0;
 
    // variable that counts total
    // numbers greater 2
    int x = 0;
     
    // loop to convert all numbers greater
    // than 2 to a range between 0 to 2.
    for (int i = 0; i < n; i++)
    {
        if (a[i] > 2) {
             
            // number greater than 2 gets
            // converted to a number between 0 to 2.
            a[i] = (a[i] + 1) % 3;
            x += 1;
        }
    }
 
    // variables to count 3 possible ways
    // to make all elements equal after
    // reducing them to range [0, 2]
    int c0 = 0, c1 = 0, c2 = 0;
 
    // loop that counts total cost to
    // make all elements equal to 0.
    for (int i = 0; i < n; i++)
    {
        if (a[i] == 1) {
             
            // since we will have to use the
            // operation 2 times to convert 1 to 0
            // (1+1)%3=2 and then (2+1)%3=0
            c0 += 2;
        }
 
        // here we use it once since (2+1%3=0)       
        else if (a[i] == 2)
            c0 += 1;
    }
 
    // loop that counts total cost to
    // make all elements equal to 1
    for (int i = 0; i < n; i++)
    {
        // since (2+1%3=0) and (0+1%3=1)
        if (a[i] == 2)
            c1 += 2;
         
        // since (0+1%3=1)
        else if (a[i] == 0)   
            c1 += 1;
    }
 
    // loop that counts total cost
    // to make all elements equal to 2
    for (int i = 0; i < n; i++) {
 
        // since 0+1%3=1 and 1+1%3=2
        if (a[i] == 0)
            c2 += 2;       
        else if (a[i] == 1)
            c2 += 1;        
    }
 
    // finally the one with minimum
    // cost will be our answer
    return x + min({ c0, c1, c2 });
}
 
// Driver program to run above function
int main()
{
    int a[] = { 98, 4, 3, 1 };
    int n = sizeof(a)/sizeof(a[0]);
    cout << mincost(a, n)<<" units";
    return 0;
}


Java




// Java program to find minimum
// cost to equalize an array
// with increment under
// modulo 3 operation.
import java.io.*;
 
class GFG
{
     
// Function to find minimum cost
static int mincost(int a[], int n)
{
    int c = 1;
     
    // loop to check whether all
    // elements are equal or not
    for (int i = 0; i < n - 1; i++)
        if (a[i] == a[i + 1])
            c++;
     
    // A special case when all
    // elements are equal
    if (c == n)
        return 0;
 
    // variable that counts total
    // numbers greater 2
    int x = 0;
     
    // loop to convert all numbers
    // greater than 2 to a range
    // between 0 to 2.
    for (int i = 0; i < n - 1; i++)
    {
        if (a[i] > 2)
        {
             
            // number greater than 2
            // gets converted to a
            // number between 0 to 2.
            a[i] = (a[i] + 1) % 3;
            x += 1;
        }
    }
 
    // variables to count 3 possible
    // ways to make all elements equal
    // after reducing them to range [0, 2]
    int c0 = 0, c1 = 0, c2 = 0;
 
    // loop that counts total cost to
    // make all elements equal to 0.
    for (int i = 0; i < n - 1; i++)
    {
        if (a[i] == 1)
        {
             
            // since we will have to
            // use the operation 2
            // times to convert 1 to 0
            // (1+1)%3=2 and then (2+1)%3=0
            c0 += 2;
        }
 
        // here we use it
        // once since (2+1%3=0)
        else if (a[i] == 2)
            c0 += 1;
    }
 
    // loop that counts total cost to
    // make all elements equal to 1
    for (int i = 0; i < n - 1; i++)
    {
        // since (2+1%3=0)
        // and (0+1%3=1)
        if (a[i] == 2)
            c1 += 2;
         
        // since (0+1%3=1)
        else if (a[i] == 0)
            c1 += 1;
    }
 
    // loop that counts total cost
    // to make all elements equal to 2
    for (int i = 0; i < n - 1; i++)
    {
 
        // since 0+1%3=1
        // and 1+1%3=2
        if (a[i] == 0)
            c2 += 2;    
        else if (a[i] == 1)
            c2 += 1;        
    }
 
    // finally the one with minimum
    // cost will be our answer
    return x + Math.min(c0,
               Math.min(c1, c2));
}
 
// Driver Code
public static void main (String[] args)
{
    int a[] = new int[]{98, 4, 3, 1};
    int n = a.length;
    System.out.println(mincost(a, n) +
                       " " + "units");
}
}
 
// This code is contributed by ajit


Python3




# Python code to illustrate above approach
# function to calculate minimum cost
def mincost(a, n):
 
    # loop to check whether all elements
    # are equal or not
    c = 1
    for i in range(0, n-1):
        if (a[i] == a[i + 1]):
            c += 1
 
    # A special case when all elements
    # are equal
    if (c == n):
        return 0
     
    # loop to count total no of conversion
    # of numbers greater than 2 to a
    # number between 0 to 2.
    x = 0
    for i in range(n):
        if a[i]>2:
            a[i]=(a[i]+1)% 3
            x += 1
             
    # variables to count 3 possible ways
    # to make all elements equal after
    # reducing them to range [0, 2]
    c0 = c1 = c2 = 0   
     
    # loop that counts total cost to
    # make all elements equal to 0.
    for i in a:
        if (i == 1):
            c0+= 2
        elif (i == 2):
            c0+= 1
 
    # loop that counts total cost to
    # make all elements equal to 1.    
    for i in a:
        if (i == 0):
            c1+= 1
        elif (i == 2):
            c1+= 2
             
    # loop that counts total cost to
    # make all elements equal to 2.
    for i in a:
        if (i == 0):
            c2+= 2
        elif (i == 1):
            c2+= 1
             
    # finally the one with minimum cost
    # plus the extra cost to convert numbers
    # greater than 2 will be our answer
    return min(c1, c2, c0)+x
 
# Driver code
n = 4
a = [98, 4, 3, 1]
c = 1
print(mincost(a, n), "units")


C#




// C# program to find minimum cost to
// equalize an array with increment
// under modulo 3 operation.
using System;
 
class GFG {
 
// Function to find minimum cost   
static int mincost(int []a, int n)
{
    int c = 1;
     
    // loop to check whether all
    // elements are equal or not
    for (int i = 0; i < n - 1; i++)
        if (a[i] == a[i + 1])
            c++;
     
    // A special case when all
    // elements are equal
    if (c == n)
        return 0;
 
    // variable that counts total
    // numbers greater 2
    int x = 0;
     
    // loop to convert all numbers greater
    // than 2 to a range between 0 to 2.
    for (int i = 0; i < n - 1; i++)
    {
        if (a[i] > 2) {
             
            // number greater than 2 gets
            // converted to a number
            // between 0 to 2.
            a[i] = (a[i] + 1) % 3;
            x += 1;
        }
    }
 
    // variables to count 3 possible ways
    // to make all elements equal after
    // reducing them to range [0, 2]
    int c0 = 0, c1 = 0, c2 = 0;
 
    // loop that counts total cost to
    // make all elements equal to 0.
    for (int i = 0; i < n - 1; i++)
    {
        if (a[i] == 1)
        {
             
            // since we will have to use the
            // operation 2 times to convert 1 to 0
            // (1+1)%3=2 and then (2+1)%3=0
            c0 += 2;
        }
 
        // here we use it once since (2+1%3=0)    
        else if (a[i] == 2)
            c0 += 1;
    }
 
    // loop that counts total cost to
    // make all elements equal to 1
    for (int i = 0; i < n - 1; i++)
    {
        // since (2+1%3=0) and (0+1%3=1)
        if (a[i] == 2)
            c1 += 2;
         
        // since (0+1%3=1)
        else if (a[i] == 0)
            c1 += 1;
    }
 
    // loop that counts total cost
    // to make all elements equal to 2
    for (int i = 0; i < n - 1; i++)
    {
 
        // since 0+1%3=1 and 1+1%3=2
        if (a[i] == 0)
            c2 += 2;    
        else if (a[i] == 1)
            c2 += 1;        
    }
 
    // finally the one with minimum
    // cost will be our answer
    return x + Math.Min(c0,
               Math.Min(c1, c2) );
}
 
// Driver Code
public static void Main()
{
        int []a = new int[]{98, 4, 3, 1};
        int n = a.Length;
        Console.Write(mincost(a, n) +
                      " " + "units");
         
}
}
 
// This code is contributed by Sam007.


PHP




<?php
// PHP program to find minimum
// cost to equalize an array
// with increment under modulo
// 3 operation.
function mincost($a, $n)
{
    $c = 1;
     
    // loop to check whether all
    // elements are equal or not
    for ($i = 0; $i < $n; $i++)
            $c++;
     
    // A special case when all
    // elements are equal
    if ($c == $n)
        return 0;
 
    // variable that counts
    // total numbers greater 2
    $x = 0;
     
    // loop to convert all
    // numbers greater than 2
    // to a range between 0 to 2.
    for ($i = 0; $i < $n; $i++)
    {
        if ($a[$i] > 2)
        {
             
            // number greater than 2
            // gets converted to a
            // number between 0 to 2.
            $a[$i] = ($a[$i] + 1) % 3;
            $x += 1;
        }
    }
 
    // variables to count 3
    // possible ways to make
    // all elements equal after
    // reducing them to range [0, 2]
    $c0 = 0; $c1 = 0; $c2 = 0;
 
    // loop that counts total
    // cost to make all elements
    // equal to 0.
    for ($i = 0; $i < $n; $i++)
    {
        if ($a[$i] == 1)
        {
             
            // since we will have to
            // use the operation 2
            // times to convert 1 to 0
            // (1+1)%3=2 and then (2+1)%3=0
            $c0 += 2;
        }
 
        // here we use it
        // once since (2+1%3=0)
        else if ($a[$i] == 2)
            $c0 += 1;
    }
 
    // loop that counts total
    // cost to make all
    // elements equal to 1
    for ($i = 0; $i < $n; $i++)
    {
        // since (2+1%3=0) and
        // (0+1%3=1)
        if ($a[$i] == 2)
            $c1 += 2;
         
        // since (0+1%3=1)
        else if ($a[$i] == 0)
            $c1 += 1;
    }
 
    // loop that counts total
    // cost to make all
    // elements equal to 2
    for ($i = 0; $i < $n; $i++)
    {
 
        // since 0+1%3=1
        // and 1+1%3=2
        if ($a[$i] == 0)
            $c2 += 2;
        else if ($a[$i] == 1)
            $c2 += 1;    
    }
 
    // finally the one with
    // minimum cost will
    // be our answer
    return $x + min($c0, $c1, $c2 );
}
 
// Driver Code
$a = array(98, 4, 3, 1);
$n = sizeof($a);
echo mincost($a, $n), " units";
 
// This code is contributed by ajit
?>


Javascript




<script>
 
// Javascript program to find minimum cost to
// equalize an array with increment under
// modulo 3 operation.
function mincost(a, n)
{
    let c = 1;
     
    // Loop to check whether all
    // elements are equal or not
    for(let i = 0; i < n; i++)
        if (a[i] == a[i + 1])
            c++;
     
    // A special case when all
    // elements are equal
    if (c == n)
        return 0;
 
    // Variable that counts total
    // numbers greater 2
    let x = 0;
     
    // Loop to convert all numbers greater
    // than 2 to a range between 0 to 2.
    for(let i = 0; i < n; i++)
    {
        if (a[i] > 2)
        {
             
            // Number greater than 2 gets
            // converted to a number between 0 to 2.
            a[i] = (a[i] + 1) % 3;
            x += 1;
        }
    }
 
    // Variables to count 3 possible ways
    // to make all elements equal after
    // reducing them to range [0, 2]
    let c0 = 0, c1 = 0, c2 = 0;
 
    // Loop that counts total cost to
    // make all elements equal to 0.
    for(let i = 0; i < n; i++)
    {
        if (a[i] == 1)
        {
             
            // Since we will have to use the
            // operation 2 times to convert 1 to 0
            // (1+1)%3=2 and then (2+1)%3=0
            c0 += 2;
        }
 
        // Here we use it once since (2+1%3=0)       
        else if (a[i] == 2)
            c0 += 1;
    }
 
    // Loop that counts total cost to
    // make all elements equal to 1
    for(let i = 0; i < n; i++)
    {
         
        // Since (2+1%3=0) and (0+1%3=1)
        if (a[i] == 2)
            c1 += 2;
         
        // Since (0+1%3=1)
        else if (a[i] == 0)   
            c1 += 1;
    }
 
    // Loop that counts total cost
    // to make all elements equal to 2
    for(let i = 0; i < n; i++)
    {
         
        // Since 0+1%3=1 and 1+1%3=2
        if (a[i] == 0)
            c2 += 2;       
        else if (a[i] == 1)
            c2 += 1;        
    }
 
    // Finally the one with minimum
    // cost will be our answer
    let y = Math.min(c0, c1);
    return x + Math.min(y, c2);
}
 
// Driver code
let a = [ 98, 4, 3, 1 ];
let n = a.length;
 
document.write(mincost(a, n) + " units");
 
// This code is contributed by subham348
 
</script>


Output

6 units

Complexity Analysis:

  • Time Complexity: O(n)
  • Space Complexity: O(1) since constant variables are being used.


Similar Reads

Minimizing operations for equalizing Array elements
Given an array A[] of length N (N&gt;=2) along with an integer X. You are allowed to select two elements A[i] and A[j], such that the absolute difference between their indices is X. Formally, abs (i - j) = X and then decrement one element and increment the other, the task is to output the minimum number of operations required to make all elements o
8 min read
Minimize increment or increment and decrement of Pair to make all Array elements equal
Given an array arr[] of size N, the task is to minimize the number of steps to make all the array elements equal by performing the following operations: Choose an element of the array and increase it by 1.Select two elements simultaneously (arr[i], arr[j]) increase arr[i] by 1 and decrease arr[j] by 1. Examples: Input: arr = [4, 2, 4, 6]Output: 2Ex
8 min read
Minimize increment/decrement of Array elements to make each modulo K equal
Given an array arr[] of length N and an integer K. In each operation any element(say arr[i]) can be selected from the array and can be changed to arr[i] + 1 or arr[i] - 1. The task is to find the minimum number of operations required to perform on the array such that each value of the array modulo K remains the same. Examples: Input: arr[] = {4, 5,
10 min read
Nearest smaller number to N having multiplicative inverse under modulo N equal to that number
Given a prime number N, the task is to find the closest smaller number than N such that modulo multiplicative inverse of a number under modulo N is equal to the number itself. Examples: Input: N = 7Output: 6Explanation:Modulo multiplicative inverse of all possible natural numbers from 1 to less than N are:Modulo multiplicative inverse of 1 under mo
3 min read
Expressing a fraction as a natural number under modulo 'm'
Given two integers A and B where A is not divisible by B, the task is to express A / B as a natural number modulo m where m = 1000000007. Note: This representation is useful where we need to express Probability of an event, Area of Curves and polygons etc.Examples: Input: A = 2, B = 6 Output: 333333336Input: A = 4, B = 5 Output: 600000005 Approach:
12 min read
Find Square Root under Modulo p | (When p is product of two primes in the form 4*i + 3)
Given an integer N and an integer P denoting the product of two primes, the task is to find all possible Square Root of N under modulo P if it exists. It is given that P is the product of p1 and p2, where p1 and p2 are prime numbers of the form 4i + 3 where i is any integer. Some examples of such prime numbers are (7, 11, 19, 23, 31). Examples: Inp
17 min read
Compute n! under modulo p
Given a large number n and a prime p, how to efficiently compute n! % p?Examples : Input: n = 5, p = 13 Output: 3 5! = 120 and 120 % 13 = 3 Input: n = 6, p = 11 Output: 5 6! = 720 and 720 % 11 = 5 A Naive Solution is to first compute n!, then compute n! % p. This solution works fine when the value of n! is small. The value of n! % p is generally ne
22 min read
Euler's criterion (Check if square root under modulo p exists)
Given a number 'n' and a prime p, find if square root of n under modulo p exists or not. A number x is square root of n under modulo p if (x*x)%p = n%p. Examples : Input: n = 2, p = 5 Output: false There doesn't exist a number x such that (x*x)%5 is 2 Input: n = 2, p = 7 Output: true There exists a number x such that (x*x)%7 is 2. The number is 3.
11 min read
Find Square Root under Modulo p | Set 1 (When p is in form of 4*i + 3)
Given a number 'n' and a prime 'p', find square root of n under modulo p if it exists. It may be given that p is in the form for 4*i + 3 (OR p % 4 = 3) where i is an integer. Examples of such primes are 7, 11, 19, 23, 31, ... etc,Examples: Input: n = 2, p = 7Output: 3 or 4Explanation: 3 and 4 both are square roots of 2 under modulo 7 because (3*3)
14 min read
Find Square Root under Modulo p | Set 2 (Shanks Tonelli algorithm)
Given a number ā€˜nā€™ and a prime ā€˜pā€™, find square root of n under modulo p if it exists. Examples: Input: n = 2, p = 113 Output: 62 62^2 = 3844 and 3844 % 113 = 2 Input: n = 2, p = 7 Output: 3 or 4 3 and 4 both are square roots of 2 under modulo 7 because (3*3) % 7 = 2 and (4*4) % 7 = 2 Input: n = 2, p = 5 Output: Square root doesn't exist We have di
20 min read
Article Tags :
Practice Tags :