Leetcode845 最长的山脉
JAVA 递归描述:
int re = 0; public final int longestMountain(int[] arr) { if (arr.length < 3) return 0; longest(arr, 1, 0, 0); return re == 0 ? re : re + 1; } private final void longest(int[] arr, int end, int upLen, int downLen) { if (end == arr.length) { if (downLen > 0) re = Math.max(re, upLen + downLen); return; } if (arr[end - 1] < arr[end]) { if (downLen > 0) { re = Math.max(re, upLen + downLen + 1); longest(arr, end + 1, 0, 0); } else longest(arr, end + 1, upLen + 1, 0); return; } if (arr[end - 1] == arr[end]) { if (downLen > 0) re = Math.max(re, upLen + downLen); longest(arr, end + 1, 0, 0); return; } if (upLen > 0) { re = Math.max(re, upLen + downLen); longest(arr, end + 1, upLen, downLen + 1); } else longest(arr, end + 1, 0, 0); }
JS 递推描述:
/** * @param {number[]} arr * @return {number} */ var longestMountain = function (arr) { if ((!arr) || arr.length < 3) return 0; let up = 0, down = 0, re = 0; for (let i = 1; i < arr.length; i++) { if (arr[i] > arr[i - 1]) { if (down > 0) { re = Math.max(re,up + down + 1); up = 1; down = 0; } else up++; continue; } if (arr[i] == arr[i - 1]) { if (down > 0) { re = Math.max(re,up + down + 1); up = 0; down = 0; } else up = 0; continue; } if (up != 0) { down++; re = Math.max(re,up + down + 1); } } return re; };
当你看清人们的真相,于是你知道了,你可以忍受孤独