Similar Problems
Similar Problems not available
Maximize Greatness Of An Array - Leetcode Solution
Companies:
LeetCode: Maximize Greatness Of An Array Leetcode Solution
Difficulty: Medium
Topics: greedy sorting array two-pointers
The problem "Maximize Greatness Of An Array" on LeetCode asks you to find the maximum greatness of an array by adding or subtracting a single digit from each element of the array, as many times as desired.
To solve this problem, we can use a greedy approach. First, we need to find the maximum and minimum elements in the array. We will then try to make the maximum element as large as possible by repeatedly adding 9 until we reach a limit (i.e., the maximum value of the datatype). Similarly, we will try to make the minimum element as small as possible by subtracting 9 until we reach a limit (i.e., the minimum value of the datatype).
After these two steps, we will have the maximum and minimum possible values for each element of the array. Finally, we can calculate the greatness of the array by subtracting the minimum possible value from the maximum possible value for each element, and summing those differences.
Here is the Python 3 solution for this problem:
class Solution:
def maxGreatness(self, nums: List[int]) -> int:
max_n = float('-inf')
min_n = float('inf')
for num in nums:
max_n = max(max_n, num)
min_n = min(min_n, num)
max_diff = 0
for i in range(len(nums)):
max_diff += max(nums[i] - min_n, max_n - nums[i])
return max_diff
In the first loop, we find the maximum and minimum elements of the array. In the second loop, we calculate the maximum possible difference for each element by taking the maximum difference between the element and the minimum element, and the maximum difference between the maximum element and the element. Finally, we sum up all these differences to get the maximum greatness of the array.
Maximize Greatness Of An Array Solution Code
1