LeetCode 题解工作台
最佳观光组合
给你一个正整数数组 values ,其中 values[i] 表示第 i 个观光景点的评分,并且两个景点 i 和 j 之间的 距离 为 j - i 。 一对景点( i )组成的观光组合的得分为 values[i] + values[j] + i - j ,也就是景点的评分之和 减去 它们两者之间的距…
2
题型
6
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们可以从左到右枚举 ,同时维护 左侧元素中 $values[i] + i$ 的最大值 ,这样对于每个 ,最大得分为 $mx + values[j] - j$。我们取所有位置的最大得分的最大值即为答案。 时间复杂度 ,其中 为数组 的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个正整数数组 values,其中 values[i] 表示第 i 个观光景点的评分,并且两个景点 i 和 j 之间的 距离 为 j - i。
一对景点(i < j)组成的观光组合的得分为 values[i] + values[j] + i - j ,也就是景点的评分之和 减去 它们两者之间的距离。
返回一对观光景点能取得的最高分。
示例 1:
输入:values = [8,1,5,2,6] 输出:11 解释:i = 0, j = 2, values[i] + values[j] + i - j = 8 + 5 + 0 - 2 = 11
示例 2:
输入:values = [1,2] 输出:2
提示:
2 <= values.length <= 5 * 1041 <= values[i] <= 1000
解题思路
方法一:枚举
我们可以从左到右枚举 ,同时维护 左侧元素中 的最大值 ,这样对于每个 ,最大得分为 。我们取所有位置的最大得分的最大值即为答案。
时间复杂度 ,其中 为数组 的长度。空间复杂度 。
class Solution:
def maxScoreSightseeingPair(self, values: List[int]) -> int:
ans = mx = 0
for j, x in enumerate(values):
ans = max(ans, mx + x - j)
mx = max(mx, x + j)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Are you able to simplify the score formula to support a dynamic programming approach?
- question_mark
Can you track the best candidate so far in a single pass without extra arrays?
- question_mark
How do you ensure your solution handles the largest input sizes efficiently?
常见陷阱
外企场景- error
Forgetting to separate i and j components in the score, leading to nested loops and O(n^2) time.
- error
Updating the running maximum after computing the score for j instead of before.
- error
Incorrectly handling arrays of length 2 or when all values are identical.
进阶变体
外企场景- arrow_right_alt
Return not just the max score but also the indices of the best sightseeing pair.
- arrow_right_alt
Extend the problem to allow skipping certain spots or weighting distances differently.
- arrow_right_alt
Compute the k highest scores from multiple non-overlapping sightseeing pairs.