题目描述:
数组里的山谷是指一个数组A中的连续子数组B满足以下条件:
(1)B.length>=3;
(2)存在满足:0<i<B.length-1并且B[0]>B[1]>…>B[i-1]>B[i]<B[i+1]<…<B[B.length-1];
现给定一个整形数组A,找出数组A里的最长山谷B的长度,如果没有,则输出0.
思想:
- 分段统计,统计连续上升的个数和连续下降的个数
- 二者相关即为总的
- 注意,出现不符合要求(先下降后上升)的情况复位即可
public class test1 {
public static int longestMoutain(int[] nums) {
int res = 0, up = 0, down = 0;
for(int i = 1; i < nums.length; i++) {
//如果up>0,说明上升过程,然后出现一个下降,那么复位。。连续(先下降再上升)中断
//或者左右相等,直接复位
if((up > 0 && nums[i-1] > nums[i]) || nums[i-1] == nums[i])
up = down = 0;
//统计连续上升
if(nums[i-1] < nums[i])
up++;
//统计下降
if(nums[i-1] > nums[i])
down++;
//既有上升区间又有下降区间,符合要求,更新res
if(up > 0 && down > 0 && up + down + 1 > res)
res = up + down + 1;
}
return res;
}
public static void main(String[] args) {
int[] nums = {5,4,3,2,1,2,3,4,5};
int result = longestMoutain(nums);
System.out.println(result);
}
}
//打印结果
9