1. 程式人生 > >計算最長凹谷

計算最長凹谷

有一維陣列X = [8,5,1,6,7,7,3,5],我們把它畫到座標系中,其中凹下去的部分我們稱為X陣列的凹谷陣列Y,其中凹陷的長度即為凹谷陣列的長度(Y的長度大於3),其中持平的部分不計入凹谷陣列的長度。如下所示,X有兩個凹谷陣列Y1 = [8,5,1,6,7]Y2 = [7,3,5],長度分別為53。我們則需要返回這個陣列中的最長凹谷陣列的長度,即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 *********/
	}
}