LeetCode 题解工作台

高度互不相同的最大塔高和

给你一个数组 maximumHeight ,其中 maximumHeight[i] 表示第 i 座塔可以达到的 最大 高度。 你的任务是给每一座塔分别设置一个高度,使得: 第 i 座塔的高度是一个正整数,且不超过 maximumHeight[i] 。 所有塔的高度互不相同。 请你返回设置完所有塔的高…

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 贪心·invariant

bolt

答案摘要

我们可以将塔的最大高度按照从大到小排序,然后从最大高度开始逐个分配高度,用一个变量 记录当前分配的最大高度。 如果当前高度 大于 $mx - 1$,则将 更新为 $mx - 1$。此时如果 小于等于 ,说明无法分配高度,直接返回 。否则,我们将 加到答案中,并更新 为 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个数组 maximumHeight ,其中 maximumHeight[i] 表示第 i 座塔可以达到的 最大 高度。

你的任务是给每一座塔分别设置一个高度,使得:

  1. i 座塔的高度是一个正整数,且不超过 maximumHeight[i] 。
  2. 所有塔的高度互不相同。

请你返回设置完所有塔的高度后,可以达到的 最大 总高度。如果没有合法的设置,返回 -1 。

 

示例 1:

输入:maximumHeight = [2,3,4,3]

输出:10

解释:

我们可以将塔的高度设置为:[1, 2, 4, 3] 。

示例 2:

输入:maximumHeight = [15,10]

输出:25

解释:

我们可以将塔的高度设置为:[15, 10] 。

示例 3:

输入:maximumHeight = [2,2,1]

输出:-1

解释:

无法设置塔的高度为正整数且高度互不相同。

 

提示:

  • 1 <= maximumHeight.length <= 105
  • 1 <= maximumHeight[i] <= 109
lightbulb

解题思路

方法一:排序 + 贪心

我们可以将塔的最大高度按照从大到小排序,然后从最大高度开始逐个分配高度,用一个变量 mxmx 记录当前分配的最大高度。

如果当前高度 xx 大于 mx1mx - 1,则将 xx 更新为 mx1mx - 1。此时如果 xx 小于等于 00,说明无法分配高度,直接返回 1-1。否则,我们将 xx 加到答案中,并更新 mxmxxx

最后返回答案即可。

时间复杂度 O(n×logn)O(n \times \log n),空间复杂度 O(logn)O(\log n)。其中 nn 是数组 maximumHeight\textit{maximumHeight} 的长度。

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
    def maximumTotalSum(self, maximumHeight: List[int]) -> int:
        maximumHeight.sort()
        ans, mx = 0, inf
        for x in maximumHeight[::-1]:
            x = min(x, mx - 1)
            if x <= 0:
                return -1
            ans += x
            mx = x
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate considers sorting maximumHeight in descending order to enable greedy height assignment.

  • question_mark

    Candidate validates each assignment to ensure the uniqueness invariant is maintained.

  • question_mark

    Candidate handles impossible cases early by returning -1 when constraints cannot be satisfied.

warning

常见陷阱

外企场景
  • error

    Failing to check uniqueness when assigning heights, leading to duplicate tower heights.

  • error

    Assigning a height larger than maximumHeight[i], violating the problem constraints.

  • error

    Not handling impossible scenarios, resulting in incorrect sums instead of returning -1.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Allow repeated heights but penalize duplicates in total sum calculation.

  • arrow_right_alt

    Maximize total height while minimizing the difference between tallest and shortest tower.

  • arrow_right_alt

    Restrict assignments to a continuous range starting from 1 instead of any positive integers.

help

常见问题

外企场景

高度互不相同的最大塔高和题解:贪心·invariant | LeetCode #3301 中等