LeetCode 题解工作台

到达数组末尾的最大得分

给你一个长度为 n 的整数数组 nums 。 你的目标是从下标 0 出发,到达下标 n - 1 处。每次你只能移动到 更大 的下标处。 从下标 i 跳到下标 j 的得分为 (j - i) * nums[i] 。 请你返回你到达最后一个下标处能得到的 最大总得分 。 示例 1: 输入: nums = …

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 贪心·invariant

bolt

答案摘要

假设我们从下标 ,跳到下标 ,那么得分为 $(j - i) \times \text{nums}[i]$。这相当于我们走了 $j - i$ 步,每一步都得到了 的得分。然后我们从 继续跳到下一个下标 ,得分为 $(k - j) \times \text{nums}[j]$,以此类推。如果 $nums[i] \gt nums[j]$,那么我们就不应该从 跳到 ,因为这样得到的得分一定比从 直…

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个长度为 n 的整数数组 nums 。

你的目标是从下标 0 出发,到达下标 n - 1 处。每次你只能移动到 更大 的下标处。

从下标 i 跳到下标 j 的得分为 (j - i) * nums[i] 。

请你返回你到达最后一个下标处能得到的 最大总得分 。

 

示例 1:

输入:nums = [1,3,1,5]

输出:7

解释:

一开始跳到下标 1 处,然后跳到最后一个下标处。总得分为 1 * 1 + 2 * 3 = 7 。

示例 2:

输入:nums = [4,3,1,3,2]

输出:16

解释:

直接跳到最后一个下标处。总得分为 4 * 4 = 16 。

 

提示:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 105
lightbulb

解题思路

方法一:贪心

假设我们从下标 ii,跳到下标 jj,那么得分为 (ji)×nums[i](j - i) \times \text{nums}[i]。这相当于我们走了 jij - i 步,每一步都得到了 nums[i]\text{nums}[i] 的得分。然后我们从 jj 继续跳到下一个下标 kk,得分为 (kj)×nums[j](k - j) \times \text{nums}[j],以此类推。如果 nums[i]>nums[j]nums[i] \gt nums[j],那么我们就不应该从 ii 跳到 jj,因为这样得到的得分一定比从 ii 直接跳到 kk 得到的得分要少。因此,我们每一次应该跳到下一个比当前下标对应的值更大的下标。

我们可以维护一个变量 mxmx,表示当前为止,我们遇到的最大的 nums[i]\text{nums}[i] 的值。然后我们从左到右遍历数组,直到倒数第二个元素,每次更新 mxmx,并且累加得分。

遍历结束后,我们得到的就是最大的总得分。

时间复杂度 O(n)O(n),其中 nn 为数组 nums\text{nums} 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
class Solution:
    def findMaximumScore(self, nums: List[int]) -> int:
        ans = mx = 0
        for x in nums[:-1]:
            mx = max(mx, x)
            ans += mx
        return ans
speed

复杂度分析

指标
时间complexity can range from O(n^2) for naive evaluation to O(n) with a monotonic queue or optimized approach. Space complexity is O(n) for storing scores or O(1) if using in-place tracking with a pointer strategy.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate attempts all jumps naively without leveraging greedy invariant.

  • question_mark

    Candidate fails to maintain cumulative maximum score while iterating.

  • question_mark

    Candidate overlooks distance multiplier in scoring, reducing total score.

warning

常见陷阱

外企场景
  • error

    Forgetting to multiply the jump distance by nums[i], leading to incorrect score.

  • error

    Selecting a local maximum without considering future cumulative impact.

  • error

    Inefficiently scanning all indices, causing timeouts on large arrays.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Compute maximum score when jumps can skip backward but still maximize total.

  • arrow_right_alt

    Modify scoring to use sum of nums[i] instead of distance multiplier.

  • arrow_right_alt

    Restrict jumps to fixed-length steps and find maximum achievable score.

help

常见问题

外企场景

到达数组末尾的最大得分题解:贪心·invariant | LeetCode #3282 中等