LeetCode 376. Wiggle Subsequence -动态规划解法

A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.

For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.

Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.

Examples: Input: [1,7,4,9,2,5] Output: 6 The entire sequence is a
wiggle sequence.

Input: [1,17,5,10,13,15,10,5,16,8] Output: 7 There are several
subsequences that achieve this length. One is [1,17,10,13,10,16,8].

Input: [1,2,3,4,5,6,7,8,9] Output: 2

这个题目要注意的就是那个元素如果相等需要跳过,其他思路类似于之前我写的那篇文章的思路,只是判断条件变了,注意点细节就好,传送门:LeetCode 300 最长上升子序列

public class WiggleMaxLength {
    public static int max(int a, int b) {
        if (a > b)
            return a;
        else
            return b;
    }

    public static int wiggleMaxLength(int[] nums) {
        int N = nums.length;
        if (N <= 1)
            return N;
        int flag=-1;
        int Max; //记录最大值
        int keynums[] = new int[nums.length];
        if (nums[0] != nums[1]) { //初始化如果前两个元素相等那么初始值是1和2,否则初始值都是1
            Max = 2;
            keynums[0] = 1;
            keynums[1] = 2;
        } else {
            Max = 1;
            keynums[0] = 1;
            keynums[1] = 1;
        }
        for (int i = 2; i < N; i++)
            keynums[i] = 1;

        for (int i = 2; i < N; i++) {
            int temmax = 1;
            for (int j = i - 1; j >= 1; j--) {
                if (nums[i] > nums[j] && nums[j] < nums[j - 1]) { //当前元素与之前元素比较
                    temmax = max(temmax, keynums[j] + keynums[i]);


                } else if(nums[i] < nums[j] && nums[j] > nums[j - 1]){

                    temmax = max(temmax, keynums[j] + keynums[i]);

                } else if(nums[i] != nums[j]){
                    temmax = max(temmax, 2);

                } else if(nums[i]==nums[j]) {//如果元素相等,赋值给前面那个相等元素相同的值便可跳出循环
                    flag=2;
                    keynums[i]=max(temmax,keynums[j]);
                    break;
                    }

            }
            if(flag!=2)
            keynums[i] = temmax;
            flag=-1;
            if (temmax > Max)
                Max = temmax;
        }

        return Max;
    }



}

你可能感兴趣的:(算法与数据结构)