LeetCode-3350 检测相邻递增子数组Ⅱ

本文最后更新于:2025年3月6日 晚上

LeetCode-3350 检测相邻递增子数组Ⅱ

题目描述

给你一个由 n 个整数组成的数组 nums ,请你找出 k最大值,使得存在 两个 相邻 且长度为 k严格递增 子数组。具体来说,需要检查是否存在从下标 ab (a < b) 开始的 两个 子数组,并满足下述全部条件:

  • 这两个子数组 nums[a..a + k - 1]nums[b..b + k - 1] 都是 严格递增 的。
  • 这两个子数组必须是 相邻的,即 b = a + k

返回 k最大可能 值。

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

示例 1:

输入:nums = [2,5,7,8,9,2,3,4,3,1]

输出:3

解释:

  • 从下标 2 开始的子数组是 [7, 8, 9],它是严格递增的。
  • 从下标 5 开始的子数组是 [2, 3, 4],它也是严格递增的。
  • 这两个子数组是相邻的,因此 3 是满足题目条件的 最大 k 值。

示例 2:

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

输出:2

解释:

  • 从下标 0 开始的子数组是 [1, 2],它是严格递增的。
  • 从下标 2 开始的子数组是 [3, 4],它也是严格递增的。
  • 这两个子数组是相邻的,因此 2 是满足题目条件的 最大 k 值。

提示:

  • 2 <= nums.length <= 2 * 10^5
  • -10^9 <= nums[i] <= 10^9

题解

解法一

记录最大严格递增子数组的长度

组间和组内找出最大k

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
def maxIncreasingSubarrays(self, nums: List[int]) -> int:
# 得出严格递增子数组长度
lenth = 1
sub_nums = []
ans = 1
for i in range(1, len(nums)):
if nums[i] > nums[i - 1]:
lenth += 1
else:
sub_nums.append(lenth)
ans = max(ans, lenth // 2) # 子数组组内最大k值
lenth = 1
sub_nums.append(lenth) # 最后一个子数组
ans = max(ans, lenth // 2)
print(sub_nums)
# 组间最大k值
for i in range(len(sub_nums) - 1):
ans = max(ans, min(sub_nums[i], sub_nums[i + 1]))
return ans
  • 时间复杂度O(n)

  • 空间复杂度O(n)

解法二

组间求解使用临时变量记录前一最大递增子数组长度,将空间复杂度减到O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def maxIncreasingSubarrays(self, nums: List[int]) -> int:
lenth = 1
pre_lenth = 0
ans = 1
for i in range(1, len(nums)):
if nums[i] > nums[i - 1]:
lenth += 1
else:
ans = max(ans, lenth // 2, min(pre_lenth, lenth)) # 子数组组内和组建最大k值
pre_lenth = lenth
lenth = 1
ans = max(ans, lenth // 2, min(pre_lenth, lenth))
return ans

LeetCode-3350 检测相邻递增子数组Ⅱ
https://furthur509.github.io/2025/03/06/LeetCode-3350 检测相邻递增子数组Ⅱ/
作者
Yang Mingxin
发布于
2025年3月6日
许可协议