Given an integer array arr, return the length of a maximum size turbulent subarray of arr.
A subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray.
More formally, a subarray [arr[i], arr[i + 1], …, arr[j]] of arr is said to be turbulent if and only if:
For i <= k < j:
arr[k] > arr[k + 1] when k is odd, and
arr[k] < arr[k + 1] when k is even.
Or, for i <= k < j:
arr[k] > arr[k + 1] when k is even, and
arr[k] < arr[k + 1] when k is odd.
Example 1:
Input: arr = [9,4,2,10,7,8,8,1,9]
Output: 5
Explanation:
arr[1] > arr[2] < arr[3] > arr[4] < arr[5]
Example 2:
Input: arr = [4,8,12,16]
Output: 2
Example 3:
Input: arr = [100]
Output: 1
Constraints:
- 1 <= arr.length <= 4 * 104
- 0 <= arr[i] <= 109
持续数数, 遇到不符合条件的,就复位计数,继续数
代码实现(Rust):
impl Solution {
pub fn max_turbulence_size(arr: Vec<i32>) -> i32 {
if arr.len() < 3 {
if arr.len() == 2 {
if arr[0] != arr[1] {
return 2;
}
return 1;
} else {
return arr.len() as i32;
}
}
let mut ans = 0;
let mut count = 0;
let mut prev_cmp = '=';
for w in arr.windows(2) {
if w[0] == w[1] {
count = 0;
prev_cmp = '=';
} else if w[0] < w[1] {
if prev_cmp == '>' {
count += 1;
ans = ans.max(count);
} else {
count = 2;
ans = ans.max(count);
}
prev_cmp = '<';
} else if w[0] > w[1] {
if prev_cmp == '<' {
count += 1;
ans = ans.max(count);
} else {
count = 2;
ans = ans.max(count);
}
prev_cmp = '>';
}
}
if ans == 0 { 1 } else { ans }
}
}
给定一个整数数组,返回其中最大湍流子数组的长度。湍流子数组是指比较符号在相邻元素间翻转的子数组。例如,输入数组 [9,4,2,10,7,8,8,1,9] 的最大湍流子数组为 [9,4,2,10],长度为5。代码实现使用Rust语言,通过遍历数组并判断相邻元素的大小关系来找到符合条件的子数组。
701

被折叠的 条评论
为什么被折叠?



