Maximize the Total Height of Unique Towers - Problem
You're tasked with designing a futuristic city skyline! You have n towers to build, and each tower i has a maximum possible height of maximumHeight[i].
Your goal is to assign heights to all towers such that:
- Each tower has a positive integer height โค its maximum allowed height
- No two towers can have the same height (each must be unique)
- The total sum of all tower heights is maximized
Return the maximum possible sum of tower heights, or -1 if it's impossible to assign valid unique heights.
Example: If maximumHeight = [2, 3, 4, 3], you could assign heights [1, 2, 4, 3] for a total of 10, which is the maximum possible.
Input & Output
example_1.py โ Basic Case
$
Input:
[2, 3, 4, 3]
โบ
Output:
10
๐ก Note:
Assign heights [1, 3, 4, 2]. All heights are unique, within limits, and sum to 10 (maximum possible).
example_2.py โ Impossible Case
$
Input:
[1, 1, 1, 1, 1]
โบ
Output:
-1
๐ก Note:
Cannot assign unique positive heights since all towers have maximum height 1, but we need 5 different heights.
example_3.py โ Single Tower
$
Input:
[5]
โบ
Output:
5
๐ก Note:
Only one tower, assign it the maximum height 5.
Constraints
- 1 โค maximumHeight.length โค 105
- 1 โค maximumHeight[i] โค 109
- Each tower must have a positive integer height
- All assigned heights must be unique
Visualization
Tap to expand
Understanding the Visualization
1
Identify Priority
Buildings with higher limits get priority for taller assignments
2
Assign Greedily
Give each building the tallest height possible while maintaining uniqueness
3
Ensure Uniqueness
Each subsequent building gets a height 1 less than the previous
4
Check Feasibility
If any building would need height โค 0, the problem is impossible
Key Takeaway
๐ฏ Key Insight: By processing towers in descending order of their maximum heights and greedily assigning the highest available height to each, we guarantee both optimality and uniqueness.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code