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:
15
💡 Note:
Optimal assignment: heights [6,4,3,2,5]. Tower 1 can't use height 5 (already taken by tower 4), so it uses height 4. Sum = 6 + 4 + 3 + 2 + 5 = 20. Wait, let me recalculate: [5,4,3,2,1] gives sum 15.
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
Understanding the Visualization
1
Input
Array of maximum heights for each tower
2
Assign
Give each tower a unique height ≤ its maximum
3
Maximize
Find assignment with maximum total sum
Key Takeaway
🎯 Key Insight: Sort towers by max height and assign greedily to maximize the sum
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code