Maximize the Total Height of Unique Towers Problem
Description
LeetCode Problem 3301.
You are given an array maximumHeight, where maximumHeight[i] denotes the maximum height the i^th tower can be assigned.
Your task is to assign a height to each tower so that:
- The height of the
i^thtower is a positive integer and does not exceedmaximumHeight[i]. - No two towers have the same height.
Return the maximum possible total sum of the tower heights. If it's not possible to assign heights, return -1.
Example 1:
Input: maximumHeight = [2,3,4,3]
Output: 10
Explanation:
We can assign heights in the following way: [1, 2, 4, 3].
Example 2:
Input: maximumHeight = [15,10]
Output: 25
Explanation:
We can assign heights in the following way: [15, 10].
Example 3:
Input: maximumHeight = [2,2,1]
Output: -1
Explanation:
It's impossible to assign positive heights to each index so that no two towers have the same height.
Constraints:
1 <= maximumHeight.length <= 10^51 <= maximumHeight[i] <= 10^9
Solution
Approach: Sorting + Greedy
Sort the limits in descending order and hand out heights from the tallest tower down. Keep mx, the last height given out. Each tower gets min(limit, mx - 1), the largest height that is allowed and still unused. If that is not positive, no valid assignment exists and the answer is -1. Otherwise add it to the total and set mx to it.
Complexity: O(n log n) time and O(log n) space for the sort, where n is the length of maximumHeight.
class Solution:
def maximumTotalSum(self, maximumHeight: List[int]) -> int:
maximumHeight.sort()
ans, mx = 0, float("inf")
for x in maximumHeight[::-1]:
x = min(x, mx - 1)
if x <= 0:
return -1
ans += x
mx = x
return ans