Leetcode978 最长湍流子数组 DP
动态规划,递归表示:
public final int maxTurbulenceSize(int[] A) { Map<Long, Integer> cache = new HashMap<Long, Integer>(); int an = 0; for (int i = 0; i < A.length; i++) { an = Math.max(an, search(A, i, true, cache)); an = Math.max(an, search(A, i, false, cache)); } return an; } private final int search(int[] arr, int point, boolean isUp, Map<Long, Integer> cache) { if (point == 0) return 1; int re = 1; Long key = (((long) point) << 32) | (isUp == false ? 0 : 1); if (cache.containsKey(key)) return cache.get(key); if ((arr[point - 1] - arr[point] < 0 && isUp) || (arr[point - 1] - arr[point] > 0 && !isUp)) { re = Math.max(re, search(arr, point - 1, !isUp, cache) + 1); } cache.put(key, re); return re; }
递推表示:
public final int maxTurbulenceSizeDP(int[] A) { int[] dp = {1, 1}; int re = 1; for (int i = 1; i < A.length; i++) { int curr = A[i] - A[i - 1]; if (curr > 0) { dp[1] = dp[0] + 1; re = Math.max(dp[1], re); dp[0] = 1; } else if (curr < 0) { dp[0] = dp[1] + 1; re = Math.max(dp[0], re); dp[1] = 1; } else { dp[0] = 1; dp[1] = 1; } } return re; }
/** * @param {number[]} arr * @return {number} */ var maxTurbulenceSize = function (arr) { let dp = [1, 1], re = 1, len = arr.length; if (!len || len == 0) return 0; for (let i = 1; i < len; i++) { let curr = arr[i] - arr[i - 1]; if (curr > 0) { dp[1] = dp[0] + 1; re = Math.max(re, dp[1]); dp[0] = 1; } else if (curr < 0) { dp[0] = dp[1] + 1; re = Math.max(re, dp[0]); dp[1] = 1; } else { dp[0] = dp[1] = 1; } } return re; };
当你看清人们的真相,于是你知道了,你可以忍受孤独