Skip to main content

Maximize the Total Height of Unique Towers - Solution & Explanation

MediumArrayGreedySorting16 min read
Practice this problem

Problem Statement

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:

  1. The height of the ith tower is a positive integer and does not exceed maximumHeight[i].
  2. 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 <= 105
  • 1 <= maximumHeight[i] <= 109

Approach Overview

Problem 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.

Approach 1: Greedy Approach with Sorting

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.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n log n) due to sorting the array.
Space Complexity: O(1) since sorting is in-place.

Try this approach in the editor →

Approach 2: Max Heap Approach

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.

Code

Java

Python

JavaScript

Complexity

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.

Try this approach in the editor →

Approach 3: Sorting + Greedy

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.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Greedy Approach with Sorting

Time Complexity: O(n log n) due to sorting the array.
Space Complexity: O(1) since sorting is in-place.

Max Heap Approach

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.

Sorting + Greedy—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Greedy with SortingO(n log n)O(1)Best general solution. Simple logic and minimal memory usage.
Max Heap SimulationO(n log n)O(n)Useful when processing dynamically or when largest values must be retrieved repeatedly.

Video Solution

Maximize the Total Height of Unique Towers || LeetCode Biweekly Contest 140 || Leetcode Solution • codi • 1,290 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Maximize the Total Height of Unique Towers easy or hard?
Maximize the Total Height of Unique Towers is classified as a medium difficulty problem. The challenge lies in recognizing the greedy pattern that enforces strictly decreasing heights after sorting. Once that insight is clear, the implementation becomes a straightforward O(n log n) algorithm.
Maximize the Total Height of Unique Towers Python/Java solution
In Python or Java, the common implementation sorts the array in descending order and iterates once to assign heights using min(maxHeight[i], prev - 1). The algorithm maintains a variable tracking the last assigned height and accumulates the total sum. FleetCode provides implementations in Python, Java, C++, C, C#, and JavaScript.
How to solve Maximize the Total Height of Unique Towers in O(n)?
A strict O(n) solution is generally not feasible because the tower limits are unsorted and the greedy strategy relies on processing the largest limits first. Sorting the array ensures the highest constraints are handled earlier, which is necessary for maximizing the total height. The resulting optimal complexity is O(n log n).
What is the best approach for Maximize the Total Height of Unique Towers?
The best approach sorts the maximum heights in descending order and greedily assigns each tower the largest possible unique value. Each new tower receives min(maxHeight[i], previousHeight - 1) to maintain strictly decreasing heights. This guarantees the maximum possible sum while ensuring uniqueness. The algorithm runs in O(n log n) time due to sorting.
Is Maximize the Total Height of Unique Towers asked at Google/Amazon/Meta?
Greedy problems involving unique assignments and decreasing constraints appear frequently in interviews at companies like Amazon, Google, and Meta. Variants often require maximizing sums while preventing duplicates or enforcing strictly decreasing values. This problem is a typical medium‑level greedy interview question.
What data structure is used in Maximize the Total Height of Unique Towers?
The primary solution uses arrays and sorting to process tower limits from largest to smallest. An alternative implementation uses a max heap (priority queue) to repeatedly extract the largest available height. Both approaches enforce uniqueness by ensuring each chosen height is strictly smaller than the previous one.
What is the time complexity of Maximize the Total Height of Unique Towers?
The optimal greedy solution runs in O(n log n) time because the array must be sorted before assigning heights. After sorting, a single linear pass assigns heights and accumulates the total. The extra space complexity is O(1) if sorting is done in place.

Ready to solve this problem?

Practice Maximize the Total Height of Unique Towers with our built-in code editor and test cases.

Practice on FleetCode