You are given an array maximumHeight, where maximumHeight[i] denotes the maximum height the ith tower can be assigned.
Your task is to assign a height to each tower so that:
ith tower is a positive integer and does not exceed maximumHeight[i].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 <= 1051 <= maximumHeight[i] <= 109Problem Overview: You receive an array where maxHeights[i] represents the maximum allowed height of the i-th tower. You must assign each tower a positive integer height that does not exceed its limit, while ensuring every tower height is unique. The goal is to maximize the total sum of all chosen heights.
The main challenge is maintaining uniqueness without wasting large height values. If you greedily assign heights without considering conflicts, duplicates appear quickly and reduce the achievable total. The optimal strategy carefully distributes the largest valid heights first.
Approach 1: Greedy with Sorting (O(n log n) time, O(1) extra space)
Sort the array in descending order so the tower with the highest limit is processed first. Track the largest height that can still be used, initially set to the first tower's maximum. For each tower, assign min(maxHeights[i], previousHeight - 1). This guarantees uniqueness because each next tower must be strictly smaller than the previous assigned height.
If the computed height becomes <= 0, a valid configuration is impossible because all remaining towers would require non‑positive heights. Otherwise, add the assigned value to the running total and continue scanning the sorted array. Sorting ensures that large limits get priority, which maximizes the final sum. This greedy ordering works because decreasing earlier towers would only reduce the achievable total later.
This solution primarily uses operations on a sorted array combined with a classic greedy decision: always take the largest valid height available. The sorting step dominates the complexity, giving O(n log n) time and O(1) extra space if sorting in place.
Approach 2: Max Heap Simulation (O(n log n) time, O(n) space)
Another approach uses a max heap to repeatedly pick the tower with the largest remaining allowed height. Push all limits into a max heap. Each step pops the current maximum height and compares it with the previously assigned height to maintain uniqueness.
If the popped value would duplicate the previous height, reduce it to previousHeight - 1. If the adjusted value becomes non‑positive, the configuration cannot satisfy the constraints. Otherwise add it to the total and update the previous height tracker. The heap keeps the next largest candidate available at every step.
This method is conceptually straightforward because the heap naturally gives the largest available limit at each iteration. However, the extra heap operations add overhead compared to simply sorting once. The time complexity remains O(n log n) due to heap insertions and removals, with O(n) auxiliary space.
Recommended for interviews: The greedy sorting approach is the expected solution. It demonstrates recognition of a decreasing sequence constraint and the ability to enforce uniqueness using a simple invariant (nextHeight < previousHeight). Discussing why sorting first maximizes the total shows strong reasoning. Mentioning the heap variant shows awareness of alternative implementations, but the sorted greedy method is cleaner and typically preferred.
In this approach, we first sort the maximumHeight array in descending order. We attempt to assign heights starting from the largest possible unique value, decrementing if necessary, to ensure all assigned heights are unique.
If it becomes impossible to assign a unique height to any tower (i.e., when the required height becomes zero), we return -1. Otherwise, we compute the total sum of the assigned heights.
This C solution sorts the maximumHeight array in descending order. We iterate through the sorted array, ensuring each height is unique and less than or equal to its maximumHeight. If we can no longer assign a reasonable height, we return -1.
Time Complexity: O(n log n) due to sorting the array.
Space Complexity: O(1) since sorting is in-place.
This approach uses a max heap (or priority queue) to efficiently determine the next maximum available height to assign. We initially insert all the heights into a max heap.
By repeatedly extracting the maximum and assigning it if valid (and decreasing for unique assignments), we ensure the solution handles the large input size well by using the heap's properties.
This Java solution utilizes a max heap to manage the highest available valid heights, allowing efficient extraction and assignment while decrementing for uniqueness demands, offering a more complex but optimally efficient approach for larger datasets.
Java
Python
JavaScript
Time Complexity: O(n log n), stemming from heap operations per element.
Space Complexity: O(n), given the heap's size in proportion to input length.
We can sort the maximum heights of the towers in descending order, then allocate the heights one by one starting from the maximum height. Use a variable mx to record the current maximum allocated height.
If the current height x is greater than mx - 1, update x to mx - 1. If x is less than or equal to 0, it means the height cannot be allocated, and we directly return -1. Otherwise, we add x to the answer and update mx to x.
Finally, return the answer.
The time complexity is O(n times log n), and the space complexity is O(log n). Here, n is the length of the array maximumHeight.
Python
Java
C++
Go
TypeScript
| Approach | Complexity |
|---|---|
| Greedy Approach with Sorting | Time Complexity: O(n log n) due to sorting the array. |
| Max Heap Approach | Time Complexity: O(n log n), stemming from heap operations per element. |
| Sorting + Greedy | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Greedy with Sorting | O(n log n) | O(1) | Best general solution. Simple logic and minimal memory usage. |
| Max Heap Simulation | O(n log n) | O(n) | Useful when processing dynamically or when largest values must be retrieved repeatedly. |
Maximize the Total Height of Unique Towers || LeetCode Biweekly Contest 140 || Leetcode Solution • codi • 1,290 views views
Watch 9 more video solutions →Practice Maximize the Total Height of Unique Towers with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor