LeetCode 题解工作台

循环数组中相邻元素的最大差值

给你一个 循环 数组 nums ,请你找出相邻元素之间的 最大 绝对差值。 注意: 一个循环数组中,第一个元素和最后一个元素是相邻的。 示例 1: 输入: nums = [1,2,4] 输出: 3 解释: 由于 nums 是循环的, nums[0] 和 nums[2] 是相邻的,它们之间的绝对差值是…

category

1

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·driven

bolt

答案摘要

我们遍历数组 ,计算相邻元素之间的绝对差值,并维护最大的绝对差值,最后与首尾元素之间的绝对差值比较,取最大值即可。 时间复杂度 ,其中 为数组 的长度。空间复杂度 。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个 循环 数组 nums ,请你找出相邻元素之间的 最大 绝对差值。

注意:一个循环数组中,第一个元素和最后一个元素是相邻的。

 

示例 1:

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

输出:3

解释:

由于 nums 是循环的,nums[0] 和 nums[2] 是相邻的,它们之间的绝对差值是最大值 |4 - 1| = 3 。

示例 2:

输入:nums = [-5,-10,-5]

输出:5

解释:

相邻元素 nums[0] 和 nums[1] 之间的绝对差值为最大值 |-5 - (-10)| = 5 。

 

提示:

  • 2 <= nums.length <= 100
  • -100 <= nums[i] <= 100
lightbulb

解题思路

方法一:模拟

我们遍历数组 nums\textit{nums},计算相邻元素之间的绝对差值,并维护最大的绝对差值,最后与首尾元素之间的绝对差值比较,取最大值即可。

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

1
2
3
4
class Solution:
    def maxAdjacentDistance(self, nums: List[int]) -> int:
        return max(abs(a - b) for a, b in pairwise(nums + [nums[0]]))
speed

复杂度分析

指标
时间complexity is O(n) because we traverse the array once, comparing each adjacent pair. Space complexity is O(1) since we only store variables for the maximum and current differences.
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate understands array traversal and circular adjacency handling.

  • question_mark

    They correctly compute absolute differences and maintain a running maximum.

  • question_mark

    They can explain why extra data structures are unnecessary for optimal space.

warning

常见陷阱

外企场景
  • error

    Forgetting to include the difference between the last and first elements.

  • error

    Using additional arrays unnecessarily, increasing space complexity.

  • error

    Miscomputing absolute difference, leading to incorrect maximum values.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Finding the minimum absolute difference between adjacent elements in a circular array.

  • arrow_right_alt

    Computing the maximum difference in a rotated sorted array.

  • arrow_right_alt

    Handling arrays with floating-point numbers instead of integers.

help

常见问题

外企场景

循环数组中相邻元素的最大差值题解:数组·driven | LeetCode #3423 简单