Sponsored
Sponsored
To solve this problem, we can first sort the array. After sorting, for each distinct number except the smallest one, count how many times smaller numbers need to be stepped up to equal the larger ones. Iterate over the sorted array and accumulate these steps until all numbers are equal.
Time Complexity: O(n log n) due to sorting, Space Complexity: O(1) as sorting is done in place.
1function reductionOperations(nums) {
2 nums.sort((a, b) => a - b);
3 let operations = 0;
4 let distinctCount = 0;
5 for (let i = 1; i < nums.length; i++) {
6 if (nums[i] !== nums[i - 1]) {
7 distinctCount++;
8 }
9 operations += distinctCount;
10 }
11 return operations;
12}
13
14console.log(reductionOperations([5, 1, 3]));
In JavaScript, the sort method sorts the array, and then we iterate over it similarly to the other languages' solutions. The distinct count is tracked to compute and accumulate operations needed.
This approach involves counting the duplicates of each number without explicitly sorting. By iterating from the maximum value to the minimum, we calculate how many numbers need to be converted at each step by leveraging the array structure and gaps between numbers.
Time Complexity: O(n + k) where k is the maximum possible value in nums, Space Complexity: O(k) for the count array.
We maintain a count array for each potential value of the elements in nums. From the largest possible value, we calculate the cumulative operations needed by summing through the stored counts for all numbers greater than the current one.