import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @return int整型
*/
public int maxSubArrayLengthTwo (int[] nums) {
if(nums.length <= 2){
return nums.length;
}
int[] left = new int[nums.length];//左侧单调递增长度
int[] right = new int[nums.length];//右侧单调递增长度
int res = 0;
left[0] = 1;
right[nums.length - 1] = 1;
for (int i = 1; i < nums.length; i++) {
if(nums[i] > nums[i - 1]){
left[i] = left[i - 1] + 1;
}else {
left[i] = 1;
}
}
for (int i = nums.length - 2; i >= 0; i--) {
if(nums[i] < nums[i + 1]){
right[i] = right[i + 1] + 1;
}else {
right[i] = 1;
}
}
for (int i = 0; i < nums.length; i++) {
if(i == 0){//边界情况
res = nums[1] == 1 ? Math.max(res,right[i]) : Math.max(res,right[i + 1] + 1);
continue;
}
if(i == nums.length - 1){//边界情况
res = nums[nums.length - 2] == (int)Math.pow(10,5) ? Math.max(res,left[i]) : Math.max(res,left[i - 1] + 1);
continue;
}
if(nums[i + 1] - nums[i - 1] > 1){//两边可续上
res = Math.max(res,left[i - 1] + right[i + 1] + 1);
}else{//只能和其中一侧续上
if(nums[i + 1] != 1 && nums[i - 1]!= (int)Math.pow(10,5)){//左右都能选
res = Math.max(res,Math.max(left[i - 1],right[i + 1]) + 1);
}else if(nums[i + 1] == 1 && nums[i - 1]!= (int)Math.pow(10,5)){//只能选左侧
res = Math.max(res,left[i - 1] + 1);
}else if(nums[i + 1] != 1 && nums[i - 1]== (int)Math.pow(10,5)){//只能选右侧
res = Math.max(res,right[i + 1] + 1);
}else {//都选不了
res = Math.max(res,1);
}
}
}
return res;
}
}
10的5次方和1都是边界,看了下大家都没考虑这个上边界呢,估计是用例不太全吧



京公网安备 11010502036488号