Problem Description
Given an array maximumHeight where maximumHeight[i] represents the maximum height that the iᵗʰ tower can be assigned, assign a unique positive integer height to each tower (not exceeding its maximum) such that the total sum of the assigned heights is maximized. If it is not possible to assign such heights, return -1.
Key Insights
- To maximize the total height, try to assign each tower the highest possible height within its limit.
- The heights must be unique. After assigning one tower a height, subsequent towers must have strictly lower assigned heights.
- Sorting the maximum heights in descending order helps in greedily assigning the maximum valid unique height.
- If at any step the allowable height becomes less than 1, the assignment is impossible and -1 should be returned.
Space and Time Complexity
Time Complexity: O(n log n) due to the sorting operation. Space Complexity: O(n), needed for the sorted array (or O(1) if sorting in-place).
Solution
The idea is to sort the maximumHeight array in descending order. Initialize the current maximum possible height to a very large value. For each tower in the sorted array, the tower's assigned height is the minimum of its maximum height and the current maximum height allowed (which is one less than the previous assigned height). If the computed height is less than 1, then it is impossible to assign valid heights and return -1. Otherwise, add the assigned height to the total sum and update the current maximum allowed height.