Maximize the Total Height of Unique Towers - Problem

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-th tower is a positive integer and does not exceed maximumHeight[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.

Input & Output

Example 1 — Basic Case
$ Input: maximumHeight = [4,3,5]
Output: 12
💡 Note: Optimal assignment: tower 0 gets height 4, tower 1 gets height 3, tower 2 gets height 5. All heights are unique and within limits. Sum = 4 + 3 + 5 = 12.
Example 2 — Need Height Adjustment
$ Input: maximumHeight = [6,5,3,2,5]
Output: 20
💡 Note: Using greedy approach: sort towers by max height descending: [(6,0), (5,1), (5,4), (3,2), (2,3)]. Assign heights: tower 0 gets 6, tower 1 gets 5, tower 4 gets 4 (since 5 is taken), tower 2 gets 3, tower 3 gets 2. Final heights: [6,5,3,2,4]. Sum = 6 + 5 + 3 + 2 + 4 = 20.
Example 3 — Impossible Case
$ Input: maximumHeight = [1,1]
Output: -1
💡 Note: Both towers have maximum height 1, but we need unique heights. Only one tower can have height 1, making it impossible to assign unique heights to both towers.

Constraints

  • 1 ≤ maximumHeight.length ≤ 105
  • 1 ≤ maximumHeight[i] ≤ 109

Visualization

Tap to expand
Maximize Total Height of Unique Towers INPUT maximumHeight array: max: 4 i=0 max: 3 i=1 max: 5 i=2 [4, 3, 5] 3 towers with max heights ALGORITHM STEPS 1 Sort Descending [5, 4, 3] 2 Assign Greedily Each tower gets max unique 3 Process Each height = min(max, prev-1) 4 Sum Heights Return -1 if any height < 1 Assignment Process: max=5 --> assign 5 max=4 --> assign 4 max=3 --> assign 3 Total = 5+4+3 = 12 FINAL RESULT 5 h=5 4 h=4 3 h=3 All Heights Unique: OK Output: 12 Maximum Total Sum: 5 + 4 + 3 = 12 Key Insight: Sort towers by maximum height in descending order. Greedily assign each tower the highest possible unique height (min of its max height and previous assigned - 1). This ensures maximum total while maintaining uniqueness. Return -1 if any height becomes 0 or negative. TutorialsPoint - Maximize the Total Height of Unique Towers | Greedy - Sort and Assign
Asked in
Amazon 25 Google 20 Meta 15
18.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen