Skip to content

3301. Maximize the Total Height of Unique Towers 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(\texttt{sort})$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  long long maximumTotalSum(vector<int>& maximumHeight) {
    long ans = 0;
    int mn = INT_MAX;

    ranges::sort(maximumHeight, greater<>());

    for (const int height : maximumHeight) {
      const int assigned = min(height, mn - 1);
      if (assigned == 0)
        return -1;
      ans += assigned;
      mn = assigned;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public long maximumTotalSum(int[] maximumHeight) {
    long ans = 0;
    int mn = Integer.MAX_VALUE;

    Arrays.sort(maximumHeight);

    for (int i = maximumHeight.length - 1; i >= 0; --i) {
      final int assigned = Math.min(maximumHeight[i], mn - 1);
      if (assigned == 0)
        return -1;
      ans += assigned;
      mn = assigned;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def maximumTotalSum(self, maximumHeight: list[int]) -> int:
    ans = 0
    mn = math.inf

    for height in sorted(maximumHeight, reverse=True):
      assigned = min(height, mn - 1)
      if assigned == 0:
        return -1
      ans += assigned
      mn = assigned

    return ans