Minimum Operations to Make All Array Elements Equal
Try to solve the Minimum Operations to Make All Array Elements Equal problem.
We'll cover the following
Statement
You are given an array, nums
, consisting of positive integers of size n
and another array queries
of size m
. For each query queries
, the goal is to make all elements of nums
equal to queries[i]
. To achieve this, you can perform the following operation any number of times:
Increase or decrease an element of
nums
by 1.
Return an array answer
of size m
, where answer[i]
is the minimum number of operations needed to make all elements of nums
equal to queries[i]
. After processing each query, the nums
array is reset to its original state.
Constraints
n
nums.length
m
queries.length
n
,m
nums[i]
,queries[i]
Examples
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Minimum Operations to Make All Array Elements Equal
What is the output for the inputs given below?
nums = [5, 2, 8, 4]
queries = [3, 7]
[9, 11]
[8, 10]
[6, 8]
[2, 4]
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Try it yourself
Implement your solution in the following coding playground.
import java.util.*;public class Solution{public static List<Long> minOperations(int[] nums, int[] queries) {// Replace this placeholder return statement with your codereturn new ArrayList<Long>();}}
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.