LeetCode 题解工作台

增量元素之间的最大差值

给你一个下标从 0 开始的整数数组 nums ,该数组的大小为 n ,请你计算 nums[j] - nums[i] 能求得的 最大差值 ,其中 0 且 nums[i] 。 返回 最大差值 。如果不存在满足要求的 i 和 j ,返回 -1 。 示例 1: 输入: nums = [7, 1 , 5 ,4…

category

1

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·driven

bolt

答案摘要

我们用一个变量 表示当前遍历到的元素中的最小值,用一个变量 表示最大差值,初始时 为 ,而 为 。 遍历数组,对于当前遍历到的元素 ,如果 $x \gt \textit{mi}$,则更新 为 $\max(\textit{ans}, x - \textit{mi})$,否则更新 $\textit{mi} = x$。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 0 开始的整数数组 nums ,该数组的大小为 n ,请你计算 nums[j] - nums[i] 能求得的 最大差值 ,其中 0 <= i < j < nnums[i] < nums[j]

返回 最大差值 。如果不存在满足要求的 ij ,返回 -1

 

示例 1:

输入:nums = [7,1,5,4]
输出:4
解释:
最大差值出现在 i = 1 且 j = 2 时,nums[j] - nums[i] = 5 - 1 = 4 。
注意,尽管 i = 1 且 j = 0 时 ,nums[j] - nums[i] = 7 - 1 = 6 > 4 ,但 i > j 不满足题面要求,所以 6 不是有效的答案。

示例 2:

输入:nums = [9,4,3,2]
输出:-1
解释:
不存在同时满足 i < j 和 nums[i] < nums[j] 这两个条件的 i, j 组合。

示例 3:

输入:nums = [1,5,2,10]
输出:9
解释:
最大差值出现在 i = 0 且 j = 3 时,nums[j] - nums[i] = 10 - 1 = 9 。

 

提示:

  • n == nums.length
  • 2 <= n <= 1000
  • 1 <= nums[i] <= 109
lightbulb

解题思路

方法一:维护前缀最小值

我们用一个变量 mi\textit{mi} 表示当前遍历到的元素中的最小值,用一个变量 ans\textit{ans} 表示最大差值,初始时 mi\textit{mi}++\infty,而 ans\textit{ans}1-1

遍历数组,对于当前遍历到的元素 xx,如果 x>mix \gt \textit{mi},则更新 ans\textit{ans}max(ans,xmi)\max(\textit{ans}, x - \textit{mi}),否则更新 mi=x\textit{mi} = x

遍历结束后,返回 ans\textit{ans}

遍历结束后,返回 ansans

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

1
2
3
4
5
6
7
8
9
10
11
class Solution:
    def maximumDifference(self, nums: List[int]) -> int:
        mi = inf
        ans = -1
        for x in nums:
            if x > mi:
                ans = max(ans, x - mi)
            else:
                mi = x
        return ans
speed

复杂度分析

指标
时间O(n)
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Looks for a linear scan approach rather than nested loops.

  • question_mark

    Checks if candidate tracks the minimum element efficiently.

  • question_mark

    Tests understanding of handling arrays with no increasing pairs.

warning

常见陷阱

外企场景
  • error

    Using nested loops which increases time complexity to O(n^2).

  • error

    Failing to return -1 when no valid increasing pair exists.

  • error

    Incorrectly updating minimum after computing difference, missing optimal solution.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Find maximum ratio nums[j] / nums[i] with i < j and nums[i] < nums[j].

  • arrow_right_alt

    Determine maximum difference where elements must be k indices apart.

  • arrow_right_alt

    Compute maximum difference in a circular array considering wrap-around.

help

常见问题

外企场景

增量元素之间的最大差值题解:数组·driven | LeetCode #2016 简单