Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Count minimum decrement prefix or suffix or increment all operations to make Array equal to 0
Next article icon

Count of operations to make all elements of array a[] equal to its min element by performing a[i] – b[i]

Last Updated : 30 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two array a[] and b[] of size N, the task is to print the count of operations required to make all the elements of array a[i] equal to its minimum element by performing a[i] – b[i] where its always a[i] >= b[i]. If it is not possible then return -1.
Example: 
 

Input: a[] = {5, 7, 10, 5, 15} b[] = {2, 2, 1, 3, 5} 
Output: 8 
Explanation: 
Input array is a[] = 5, 7, 10, 5, 15 and b[] = 2, 2, 1, 3, 5. The minimum from a[] is 5. 
Now for a[0] we don’t have to perform any operation since its already 5. 
For i = 1, a[1] – b[1] = 7 – 2 = 5. (1 operation) 
For i = 2, a[2] – b[2] = 10 – 1 = 9 – 1 = 8 – 1 = 7 – 1 = 6 – 1 = 5 (5 operation) 
For i = 3, a[3] = 5 
For i = 4, a[4] – b[4] = 15 – 5= 10 – 5 = 5 (2 operation) 
The total number of operations required is 8.
Input: a[] = {1, 3, 2} b[] = {2, 3, 2} 
Output:-1 
Explanation: 
It is not possible to convert the array a[] into equal elements. 

Approach: To solve the problem mentioned above follow the steps given below:
 

  • Find minimum from array a[]. Initialize a variable ans = -1 that stores resultant subtractions operation.
  • Iterate from minimum element of array a[] to 0 and initialize variable curr to 0 that stores the count subtraction to make the array element equal.
  • Traverse in the array and check if a[i] is not equal to x which is the minimum element in the first array, then make it equal to minimum else update curr equal to zero.
  • Check if curr is not equal to 0 then update ans as curr finally return the ans.

Below is the implementation of above approach: 
 

C++




// C++ program to count the operations
// to make all elements of array a[]
// equal to its min element
// by performing a[i] – b[i]
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to convert all Element of
// first array equal using second array
int findMinSub(int a[], int b[], int n)
{
    // Get the minimum from first array
    int min = INT_MAX;
    for (int i = 0; i < n; i++) {
        if (a[i] < min)
            min = a[i];
    }
 
    // Variable that stores count of
    // resultant required subtraction
    // to Convert all elements equal
    int ans = -1;
 
    for (int x = min; x >= 0; x--)
 
    {
        // Stores the count subtraction to
        // make the array element
        // equal for each iteration
        int curr = 0;
 
        // Traverse the array and check if
        // a[i] is not equal to x then
        // Make it equal to minimum else
        // update current equal to zero
        for (int i = 0; i < n; i++) {
            if (a[i] != x) {
 
                if (b[i] > 0
                    && (a[i] - x) % b[i] == 0) {
                    curr += (a[i] - x) / b[i];
                }
                else {
                    curr = 0;
                    break;
                }
            }
        }
        // Check if curr is not equal to
        // zero then update the answer
        if (curr != 0) {
            ans = curr;
            break;
        }
    }
 
    return ans;
}
 
// Driver code
int main()
{
 
    int a[] = { 5, 7, 10, 5, 15 };
    int b[] = { 2, 2, 1, 3, 5 };
 
    int n = sizeof(a) / sizeof(a[0]);
 
    cout << findMinSub(a, b, n);
    return 0;
}
 
 

Java




// Java program to count the operations
// to make all elements of array a[]
// equal to its min element
// by performing a[i] – b[i]
import java.util.*;
 
class GFG{
 
// Function to convert all element of
// first array equal using second array
static int findMinSub(int a[], int b[], int n)
{
     
    // Get the minimum from first array
    int min = Integer.MAX_VALUE;
    for(int i = 0; i < n; i++)
    {
    if (a[i] < min)
        min = a[i];
    }
 
    // Variable that stores count of
    // resultant required subtraction
    // to Convert all elements equal
    int ans = -1;
 
    for(int x = min; x >= 0; x--)
    {
         
    // Stores the count subtraction
    // to make the array element
    // equal for each iteration
    int curr = 0;
         
    // Traverse the array and check
    // if a[i] is not equal to x then
    // Make it equal to minimum else
    // update current equal to zero
    for(int i = 0; i < n; i++)
    {
        if (a[i] != x)
        {
            if (b[i] > 0 &&
                (a[i] - x) % b[i] == 0)
            {
                curr += (a[i] - x) / b[i];
            }
            else
            {
                curr = 0;
                break;
            }
        }
    }
         
    // Check if curr is not equal to
    // zero then update the answer
    if (curr != 0)
    {
        ans = curr;
        break;
    }
    }
    return ans;
}
 
// Driver code
public static void main(String[] args)
{
    int a[] = { 5, 7, 10, 5, 15 };
    int b[] = { 2, 2, 1, 3, 5 };
    int n = a.length;
 
    System.out.print(findMinSub(a, b, n));
}
}
 
// This code is contributed by 29AjayKumar
 
 

Python3




# Python3 program to count the operations
# to make all elements of array a[]
# equal to its min element
# by performing a[i] – b[i]
 
# Function to convert all element of
# first array equal using second array
def findMinSub(a, b, n):
     
    # Get the minimum from first array
    min = a[0]
    for i in range(0, n):
        if a[i] < min:
            min = a[i]
             
    # Variable that stores count of
    # resultant required subtraction
    # to Convert all elements equal
    ans = -1
    for x in range(min, -1, -1):
         
        # Stores the count subtraction
        # to make the array element
        # equal for each iteration
        curr = 0
 
        # Traverse the array and check
        # if a[i] is not equal to x then
        # Make it equal to minimum else
        # update current equal to zero
        for i in range(0, n):
            if a[i] != x:
                 
                if (b[i] > 0 and
                   (a[i] - x) % b[i] == 0):
                    curr += (a[i] - x) // b[i]
                else:
                    curr = 0
                    break
 
        # Check if curr is not equal to
        # zero then update the answer
        if curr != 0:
            ans = curr
            break
         
    return ans
 
# Driver code
a = [ 5, 7, 10, 5, 15 ]
b = [ 2, 2, 1, 3, 5 ]
n = len(a)
 
print(findMinSub(a, b, n))
 
# This code is contributed by jrishabh99
 
 

C#




// C# program to count the operations
// to make all elements of array a[]
// equal to its min element
// by performing a[i] – b[i]
using System;
class GFG{
 
// Function to convert all element of
// first array equal using second array
static int findMinSub(int []a, int []b, int n)
{
     
    // Get the minimum from first array
    int min = Int32.MaxValue;
     
    for(int i = 0; i < n; i++)
    {
        if (a[i] < min)
            min = a[i];
    }
 
    // Variable that stores count of
    // resultant required subtraction
    // to Convert all elements equal
    int ans = -1;
 
    for(int x = min; x >= 0; x--)
    {
         
        // Stores the count subtraction
        // to make the array element
        // equal for each iteration
        int curr = 0;
             
        // Traverse the array and check
        // if a[i] is not equal to x then
        // Make it equal to minimum else
        // update current equal to zero
        for(int i = 0; i < n; i++)
        {
            if (a[i] != x)
            {
                if (b[i] > 0 &&
                    (a[i] - x) % b[i] == 0)
                {
                    curr += (a[i] - x) / b[i];
                }
                else
                {
                    curr = 0;
                    break;
                }
            }
        }
             
        // Check if curr is not equal to
        // zero then update the answer
        if (curr != 0)
        {
            ans = curr;
            break;
        }
    }
    return ans;
}
 
// Driver code
public static void Main()
{
    int []a = { 5, 7, 10, 5, 15 };
    int []b = { 2, 2, 1, 3, 5 };
    int n = a.Length;
 
    Console.Write(findMinSub(a, b, n));
}
}
 
// This code is contributed by Code_Mech
 
 

Javascript




<script>
// javascript program to count the operations
// to make all elements of array a
// equal to its min element
// by performing a[i] – b[i]
 
    // Function to convert all element of
    // first array equal using second array
    function findMinSub(a , b , n) {
 
        // Get the minimum from first array
        var min = Number.MAX_VALUE;
        for (i = 0; i < n; i++) {
            if (a[i] < min)
                min = a[i];
        }
 
        // Variable that stores count of
        // resultant required subtraction
        // to Convert all elements equal
        var ans = -1;
 
        for (x = min; x >= 0; x--) {
 
            // Stores the count subtraction
            // to make the array element
            // equal for each iteration
            var curr = 0;
 
            // Traverse the array and check
            // if a[i] is not equal to x then
            // Make it equal to minimum else
            // update current equal to zero
            for (i = 0; i < n; i++) {
                if (a[i] != x) {
                    if (b[i] > 0 && (a[i] - x) % b[i] == 0) {
                        curr += (a[i] - x) / b[i];
                    } else {
                        curr = 0;
                        break;
                    }
                }
            }
 
            // Check if curr is not equal to
            // zero then update the answer
            if (curr != 0) {
                ans = curr;
                break;
            }
        }
        return ans;
    }
 
    // Driver code
        var a = [ 5, 7, 10, 5, 15 ];
        var b = [ 2, 2, 1, 3, 5 ];
        var n = a.length;
 
        document.write(findMinSub(a, b, n));
 
// This code is contributed by aashish1995
</script>
 
 
Output: 
8

 

Time Complexity: O(min*n) // min is the minimum element in the array
Auxiliary Space: O(1)



Next Article
Count minimum decrement prefix or suffix or increment all operations to make Array equal to 0

S

Samdare B
Improve
Article Tags :
  • Arrays
  • Competitive Programming
  • DSA
Practice Tags :
  • Arrays

Similar Reads

  • Make the array elements equal by performing given operations minimum number of times
    Given an array arr[] of size N, the task is to make all the array elements equal by performing following operations minimum number of times: Increase all array elements of any suffix array by 1.Decrease all the elements of any suffix array by 1.Replace any array element y another. Examples: Input: a
    7 min read
  • Minimum operations required to make all elements of Array less than equal to 0
    Given an array arr[] consisting of N positive numbers, the task is to find the minimum number of operations required to make all elements of the array less than or equal to 0. In each operation, one has to pick the minimum positive element from the array and subtract all the elements of the array fr
    5 min read
  • Count of elements in array A left after performing deletion/rotation operation based on given conditions
    Given two binary arrays, A[] and B[] of size N respectively, the task is to find the number of elements in array A[] that will be left after performing the following operation until no elements can be deleted: If the starting elements of array A[] and B[] are equal, then delete both the elements.Oth
    9 min read
  • Minimum Bitwise OR operations to make any two array elements equal
    Given an array arr[] of integers and an integer K, we can perform the Bitwise OR operation between any array element and K any number of times. The task is to print the minimum number of such operations required to make any two elements of the array equal. If it is not possible to make any two eleme
    9 min read
  • Count minimum decrement prefix or suffix or increment all operations to make Array equal to 0
    Given an array arr[] of size N. The task is to make all the array elements equal to zero by applying the minimum number of operations. Following operations are allowed: Select an index i and decrease each element by 1 for the prefix up to that index.Select an index i and decrease each element by 1 f
    7 min read
  • Minimize operations to delete all elements of permutation A by removing a subsequence having order as array B
    Given two permutation arrays A[] and B[] of the first N Natural Numbers, the task is to find the minimum number of operations required to remove all array elements A[] such that in each operation remove the subsequence of array elements A[] whose order is the same as in the array B[]. Example: Input
    7 min read
  • Find the minimum number of operations required to make all array elements equal
    Given an array arr[] of size N. The task is to make all the array elements equal by applying the below operations minimum number of times: Choose a pair of indices (i, j) such that |i - j| = 1 (indices i and j are adjacent) and set arr[i] = arr[i] + |arr[i] - arr[j]|Choose a pair of indices (i, j) s
    6 min read
  • Make all Array elements equal to zero in atmost m operations
    Given an integer array A[] of size N and integer k. For a fixed value p, choose an index i (1 ≤ i ≤ n) and assign A[i] = max(0, A[i] − p), this counts as one operation, and the task is to find the smallest value of p such that all the elements of the array A[] become 0 in at most k operations. Examp
    10 min read
  • Make all array elements equal by reducing array elements to half minimum number of times
    Given an array arr[] consisting of N integers, the task is to minimize the number of operations required to make all array elements equal by converting Ai to Ai / 2. in each operation Examples: Input: arr[] = {3, 1, 1, 3}Output: 2Explanation: Reducing A0 to A0 / 2 modifies arr[] to {1, 1, 1, 3}. Red
    6 min read
  • Minimize increment-decrement operation on adjacent elements to convert Array A to B
    Given two arrays A[] and B[] consisting of N positive integers, the task is to find the minimum number of increment and decrements of adjacent array elements of the array A[] required to convert it to the array B[]. If it is not possible, then print "-1". Examples: Input: A[] = {1, 2}, B[] = {2, 1}O
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences