LeetCode 题解工作台

非递减数组的最大长度

给你一个整数数组 nums 。在一次操作中,你可以选择一个子数组,并将其替换为一个等于该子数组 最大值 的单个元素。 返回经过零次或多次操作后,数组仍为 非递减 的情况下,数组 可能的最大长度 。 子数组 是数组中一个连续、 非空 的元素序列。 示例 1: 输入: nums = [4,2,5,3,5…

category

4

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 栈·状态

bolt

答案摘要

class Solution: def maximumPossibleSize(self, nums: List[int]) -> int:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 栈·状态 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 nums。在一次操作中,你可以选择一个子数组,并将其替换为一个等于该子数组 最大值 的单个元素。

返回经过零次或多次操作后,数组仍为 非递减 的情况下,数组 可能的最大长度

子数组 是数组中一个连续、非空 的元素序列。

 

示例 1:

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

输出: 3

解释:

实现最大长度的一种方法是:

  1. 将子数组 nums[1..2] = [2, 5] 替换为 5[4, 5, 3, 5]
  2. 将子数组 nums[2..3] = [3, 5] 替换为 5[4, 5, 5]

最终数组 [4, 5, 5] 是非递减的,长度为 3。

示例 2:

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

输出: 3

解释:

无需任何操作,因为数组 [1,2,3] 已经是非递减的。

 

提示:

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

解题思路

方法一

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

复杂度分析

指标
时间complexity is O(n) as each element is pushed and popped at most once. Space complexity is O(n) for the stack in the worst case when no merges occur.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Do you notice the decreasing sequences in nums and how to manage them?

  • question_mark

    Have you considered iterating backwards to simplify merge decisions with a stack?

  • question_mark

    Can you explain how each operation affects the final array size and order?

warning

常见陷阱

外企场景
  • error

    Merging forward instead of backward may require complex lookahead logic.

  • error

    Forgetting to update the maximum when merging subarrays can yield incorrect counts.

  • error

    Ignoring equal elements can reduce the array size unnecessarily.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Count minimum operations to make the array non-decreasing instead of maximum size.

  • arrow_right_alt

    Apply the same method to multidimensional arrays along one axis using stack-based state tracking.

  • arrow_right_alt

    Restrict merges to subarrays of fixed length and compute maximum non-decreasing size.

help

常见问题

外企场景

非递减数组的最大长度题解:栈·状态 | LeetCode #3523 中等