有一维数组X = [8,5,1,6,7,7,3,5]
,我们把它画到坐标系中,其中凹下去的部分我们称为X
数组的凹谷数组Y
,其中凹陷的长度即为凹谷数组的长度(Y
的长度大于3
),其中持平的部分不计入凹谷数组的长度。如下所示,X
有两个凹谷数组Y1 = [8,5,1,6,7]
和Y2 = [7,3,5]
,长度分别为5
和3
。我们则需要返回这个数组中的最长凹谷数组的长度,即5
,如果数组中不含凹谷,则返回0
。
样例1:
输入:8 5 1 6 7 3
输出:5
package com.mr.draw;
public class test11 {
public static void main(String[] args) {
test11 a = new test11();
// int arr[] = {5,2,4,5,8,10,9,8,7,6,5,7};
// int arr[] = {2,5,5};
// int arr[] = {8,5,1,6,7,3};
// int arr[] = {3,5,8,6,7,2,1};
int arr[] = {8,8,9,8 ,6, 2, 8, 8, 10};
System.out.println(a.concaveValley(arr));
}
public int concaveValley(int[] arr) {
/********* Begin *********/
int a[] = new int[arr.length - 1];
int length[] = new int[arr.length - 1];
int n = 0;
int maxlength = 0;
for (int i = 0; i < a.length; i++) {
a[i] = arr[i + 1] - arr[i];
// System.out.println(a[i]);
}
int j = 0;
while (a[j] >= 0) {
if (j == a.length - 1) {
return 0;
}
j++;
}
outer: while (j < a.length - 1) {
int first = 0, end = 0;
for (int i = j; i < a.length; i++) {
if (a[i] < 0) {
first = i;
if (first == a.length - 1) {
break outer;
}
for (int k = first + 1; k < a.length; k++) {
if (a[k] > 0) {
if (k == a.length - 1) {
end = k;
length[n] = end - first + 2;
// System.out.println(length[n]);
j = end;
break outer;
}
for (int m = k + 1; m < a.length; m++) {
if (a[m] < 0) {
end = m;
length[n] = end - first + 1;
// System.out.println(length[n]);
n++;
j = end;
continue outer;
} else if (a[m] == 0) {
end = m;
length[n] = end - first + 1;
// System.out.println(length[n]);
n++;
j = end + 1;
continue outer;
}else if(m == a.length - 1) {
end = m;
length[n] = end - first + 2;
n++;
j = end;
break outer;
}
}
} else if (k == a.length - 1) {
break outer;
}
}
}
}
}
for (int i = 0; i < length.length - 1; i++) {
if (length[i] > maxlength) {
maxlength = length[i];
}
}
return maxlength;
/********* End *********/
}
}