[Dp] Leetcode.376. Wobble sequence

Here Insert Picture Description
States defined: dp[i]representatives designated as ithe maximum swing of the end of the sequence
as well as 0 the positive and negative involved here
so the use of up[i]memory is by far the longest with the first ione up to the end of the length of the sequence elements swing.
Similarly, the down[i]record is by far the longest at the first ilongitudinal end of the drop th element of the wobble sequence.
Whenever we find the first ielement of a rise time swinging tail sequence of updates up[i]. We now consider how to update up[i], we need to consider all of the front end of the swing in descending sequence, that is to find down[j], meet j < iand nums[i]>nums[j]. Similarly, down[i]it will be updated.

/**
 * dp[i] 的意义是以下标i结尾的最长摆动序列
 */
class Solution {
    public int wiggleMaxLength(int[] nums) {
        if (nums.length <= 1) return nums.length;
        int n = nums.length;
        int[] up = new int[n];
        int[] down = new int[n];
        for (int i = 1; i < n; i++) {
            for (int j = i - 1; j >= 0; j--) {
                if(nums[i] - nums[j] > 0){
                    up[i] = Math.max(up[i],down[j] + 1);
                }else if (nums[i] < nums[j])
                    down[i] = Math.max(down[i],up[j] + 1);
            }
        }
        return 1 + Math.max(down[nums.length - 1], up[nums.length - 1]);
    }
    public static void main(String[] args) {
        int[] nums = {1,2,3,4,5,6,7,8,9};
        System.out.println(new Solution().wiggleMaxLength(nums));//2
    }
}

Guess you like

Origin www.cnblogs.com/HoweZhan/p/12547570.html