Input: maximumHeight =[2,2,1]Output: -1Explanation:
It's impossible to assign positive heights to each index so that no two towers
have the same height.
To maximize the total height with unique heights, assign the largest possible unique heights to the towers with the largest maximum allowed heights. Sort the maximum heights, then assign the largest possible unique values from the back, ensuring no two towers have the same height and each is within its allowed maximum.
classSolution {
public:int maxTotalHeight(vector<int>& maxH) {
int n = maxH.size();
sort(maxH.begin(), maxH.end());
int prev =1e9, ans =0;
for (int i = n-1; i >=0; --i) {
prev = min(prev-1, maxH[i]);
if (prev <1) return-1;
ans += prev;
}
return ans;
}
};
classSolution {
publicintmaxTotalHeight(int[] maxH) {
Arrays.sort(maxH);
int n = maxH.length, prev = Integer.MAX_VALUE, ans = 0;
for (int i = n-1; i >= 0; i--) {
prev = Math.min(prev-1, maxH[i]);
if (prev < 1) return-1;
ans += prev;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funmaxTotalHeight(maxH: IntArray): Int {
maxH.sort()
var prev = Int.MAX_VALUE
var ans = 0for (i in maxH.size-1 downTo 0) {
prev = minOf(prev-1, maxH[i])
if (prev < 1) return -1 ans += prev
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defmaxTotalHeight(self, maximumHeight: list[int]) -> int:
maximumHeight.sort()
prev = float('inf')
ans =0for h in reversed(maximumHeight):
prev = min(prev-1, h)
if prev <1:
return-1 ans += prev
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
impl Solution {
pubfnmax_total_height(mut max_h: Vec<i32>) -> i32 {
max_h.sort();
letmut prev =i32::MAX;
letmut ans =0;
for&h in max_h.iter().rev() {
prev = prev.saturating_sub(1).min(h);
if prev <1 { return-1; }
ans += prev;
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
maxTotalHeight(maximumHeight: number[]):number {
maximumHeight.sort((a, b) =>a-b);
letprev= Number.MAX_SAFE_INTEGER, ans=0;
for (leti=maximumHeight.length-1; i>=0; i--) {
prev= Math.min(prev-1, maximumHeight[i]);
if (prev<1) return-1;
ans+=prev;
}
returnans;
}
}