LeetCode 题解工作台

相同分数的最大操作数目 I

给你一个整数数组 nums ,如果 nums 至少 包含 2 个元素,你可以执行以下操作: 选择 nums 中的前两个元素并将它们删除。 一次操作的 分数 是被删除元素的和。 在确保 所有操作分数相同 的前提下,请你求出 最多 能进行多少次操作。 请你返回按照上述要求 最多 可以进行的操作次数。 示…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·模拟

bolt

答案摘要

我们先计算前两个元素的和,记为 ,然后遍历数组,每次操作取两个元素,如果和不等于 ,则停止遍历。最后返回操作次数即可。 时间复杂度 ,其中 是数组 的长度。空间复杂度 。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 nums ,如果 nums 至少 包含 2 个元素,你可以执行以下操作:

  • 选择 nums 中的前两个元素并将它们删除。

一次操作的 分数 是被删除元素的和。

在确保 所有操作分数相同 的前提下,请你求出 最多 能进行多少次操作。

请你返回按照上述要求 最多 可以进行的操作次数。

 

示例 1:

输入:nums = [3,2,1,4,5]
输出:2
解释:我们执行以下操作:
- 删除前两个元素,分数为 3 + 2 = 5 ,nums = [1,4,5] 。
- 删除前两个元素,分数为 1 + 4 = 5 ,nums = [5] 。
由于只剩下 1 个元素,我们无法继续进行任何操作。

示例 2:

输入:nums = [3,2,6,1,4]
输出:1
解释:我们执行以下操作:
- 删除前两个元素,分数为 3 + 2 = 5 ,nums = [6,1,4] 。
由于下一次操作的分数与前一次不相等,我们无法继续进行任何操作。

 

提示:

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

解题思路

方法一:遍历

我们先计算前两个元素的和,记为 ss,然后遍历数组,每次操作取两个元素,如果和不等于 ss,则停止遍历。最后返回操作次数即可。

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

1
2
3
4
5
6
7
8
9
10
class Solution:
    def maxOperations(self, nums: List[int]) -> int:
        s = nums[0] + nums[1]
        ans, n = 0, len(nums)
        for i in range(0, n, 2):
            if i + 1 == n or nums[i] + nums[i + 1] != s:
                break
            ans += 1
        return ans
speed

复杂度分析

指标
时间complexity is O(n^2) for checking all pair sums or O(n log n) with sorting and two-pointer scanning. Space complexity is O(n) for frequency map or O(1) with two-pointer simulation.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    The interviewer may ask if all pairs must use the same sum or if sums can vary.

  • question_mark

    Expect clarification questions on array constraints and operation limits.

  • question_mark

    They might probe for edge cases like repeated numbers or minimal array length.

warning

常见陷阱

外企场景
  • error

    Assuming pairs can have different sums and miscounting operations.

  • error

    Not updating counts or pointers correctly, leading to double-counting elements.

  • error

    Forgetting to consider that array size reduces after each operation, affecting subsequent pairs.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Maximum operations with varying sums allowed for each operation.

  • arrow_right_alt

    Operations restricted to consecutive elements only, still matching the sum.

  • arrow_right_alt

    Finding minimum operations to reach a target score using Array plus Simulation.

help

常见问题

外企场景

相同分数的最大操作数目 I题解:数组·模拟 | LeetCode #3038 简单