LeetCode-in-Java

2808. Minimum Seconds to Equalize a Circular Array

Medium

You are given a 0-indexed array nums containing n integers.

At each second, you perform the following operation on the array:

Note that all the elements get replaced simultaneously.

Return the minimum number of seconds needed to make all elements in the array nums equal.

Example 1:

Input: nums = [1,2,1,2]

Output: 1

Explanation: We can equalize the array in 1 second in the following way:

Example 2:

Input: nums = [2,1,3,3,2]

Output: 2

Explanation: We can equalize the array in 2 seconds in the following way:

It can be proven that 2 seconds is the minimum amount of seconds needed for equalizing the array.

Example 3:

Input: nums = [5,5,5,5]

Output: 0

Explanation: We don’t need to perform any operations as all elements in the initial array are the same.

Constraints:

Solution

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Solution {
    public int minimumSeconds(List<Integer> nums) {
        int n = nums.size();
        int min = n / 2;
        HashMap<Integer, List<Integer>> hm = new HashMap<>();
        for (int i = 0; i < n; i++) {
            int v = nums.get(i);
            hm.computeIfAbsent(v, k -> new ArrayList<>()).add(i);
        }
        for (List<Integer> list : hm.values()) {
            if (list.size() > 1) {
                int curr = (list.get(0) + n - list.get(list.size() - 1)) / 2;
                for (int i = 1; i < list.size(); i++) {
                    curr = Math.max(curr, (list.get(i) - list.get(i - 1)) / 2);
                }
                min = Math.min(min, curr);
            }
        }
        return min;
    }
}