2602. Minimum Operations to Make All Array Elements Equal

 this is for different array based equal

You are given an array nums consisting of positive integers.

You are also given an integer array queries of size m. For the ith query, you want to make all of the elements of nums equal to queries[i]. You can perform the following operation on the array any number of times:

  • Increase or decrease an element of the array by 1.

Return an array answer of size m where answer[i] is the minimum number of operations to make all elements of nums equal to queries[i].

Note that after each query the array is reset to its original state.

 

Example 1:

Input: nums = [3,1,6,8], queries = [1,5]
Output: [14,10]
Explanation: For the first query we can do the following operations:
- Decrease nums[0] 2 times, so that nums = [1,1,6,8].
- Decrease nums[2] 5 times, so that nums = [1,1,1,8].
- Decrease nums[3] 7 times, so that nums = [1,1,1,1].
So the total number of operations for the first query is 2 + 5 + 7 = 14.
For the second query we can do the following operations:
- Increase nums[0] 2 times, so that nums = [5,1,6,8].
- Increase nums[1] 4 times, so that nums = [5,5,6,8].
- Decrease nums[2] 1 time, so that nums = [5,5,5,8].
- Decrease nums[3] 3 times, so that nums = [5,5,5,5].
So the total number of operations for the second query is 2 + 4 + 1 + 3 = 10. 
class Solution {
public List<Long> minOperations(int[] nums, int[] queries) {
Arrays.sort(nums);
int n = nums.length;
long[] prefixSum = new long[n+1];
List<Long> res = new ArrayList<>();
for(int i =0;i<n;i++){
prefixSum[i+1] = prefixSum[i] + nums[i];
}
for(int query : queries){
int idx = Arrays.binarySearch(nums,query);
if(idx < 0) idx = - idx -1;

long left = (long) query * idx - prefixSum[idx];
long right = (prefixSum[n] - prefixSum[idx]) - (long) query * (n - idx);
res.add(left + right);
}
return res;
}
}
 
 
 

this is for same array based equal 

Examples: 

Input: arr[] = [1, 2, 3]
Output: 3
Explanation:
Operation 1 : Increase all except 3rd, we get 2, 3, 3
Operation 2 : Increase all except 3rd, we get 3, 4, 3
Operation 3 : Increase all except 2nd, we get 4, 4, 4

Input: arr[] = [4, 3, 4]
Output: 2
Explanation:
Operation 1 : Increase all except 3rd, we get 5, 4, 4
Operation 2 : Increase all except 1st, we get 5, 5, 5

 

class gfg{

    public int minOpr(int[] nums){

        int n = nums.length;

        int sum = 0;

        int minVal = Arrays.stream(arr).min().getAsInt();

        for(int num : nums){

            sum += num;

        }

        return sum - n * minVal; 

 

 
 
 

Comments

Popular Posts