• 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;
    };

     

  • 相关阅读:
    js模板引擎
    浮点数正则表达式
    DbContext SQLite配置文件
    JS中的HTML片段
    WPF 使用HttpListener搭建本地web服务器
    C#调用Windows(8/10)自带的虚拟键盘
    SQLSERVER 设置默认值
    SQLSERVER存储过程基本语法
    MSSQL存储过程
    WPF手动绑定事件
  • 原文地址:https://www.cnblogs.com/niuyourou/p/14148236.html
Copyright © 2020-2023  润新知