[LeetCode] Maximize the Total Height of Unique Towers

3301. Maximize the Total Height of Unique Towers

You are given an array maximumHeight, where maximumHeight[i] denotes the maximum height the ith tower can be assigned.

Your task is to assign a height to each tower so that:

  1. The height of the ith tower is a positive integer and does not exceed maximumHeight[i].
  2. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
long long maximumTotalSum(vector<int>& maximumHeight) {
sort(begin(maximumHeight), end(maximumHeight));
long long res = maximumHeight.back();
for(int i = maximumHeight.size() - 2; i >= 0; i--) {
maximumHeight[i] = min(maximumHeight[i], maximumHeight[i+1] - 1);
if(maximumHeight[i] <= 0) return -1;
res += maximumHeight[i];
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/09/29/PS/LeetCode/maximize-the-total-height-of-unique-towers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.