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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code