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.
1def reduction_operations(nums):
2 nums.sort()
3 operations = 0
4 distinct_count = 0
5 for i in range(1, len(nums)):
6 if nums[i] != nums[i - 1]:
7 distinct_count += 1
8 operations += distinct_count
9 return operations
10
11print(reduction_operations([5, 1, 3]))
In Python, we use the list sort method to order elements, then traverse through the sorted list while counting distinct numbers. This determines how many operations are needed by incrementing the operations count based on distinct elements.
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.
public class Solution {
public int ReductionOperations(int[] nums) {
int[] count = new int[50001];
foreach (int num in nums) {
count[num]++;
}
int operations = 0, total = 0;
for (int i = 50000; i > 0; i--) {
if (count[i] > 0) {
operations += total;
total += count[i];
}
}
return operations;
}
public static void Main(string[] args) {
Solution solution = new Solution();
int[] nums = {5, 1, 3};
Console.WriteLine(solution.ReductionOperations(nums));
}
}
C# uses an integer array to maintain counts and iterates through it from top down, calculated cumulative operations by acknowledgment of all larger numbers already accounted for.