LeetCode 376.

Tags:

Complexity

  • Time complexity: O(n^2)

  • Space complexity: O(n^2)

Code

class Solution {
    public int wiggleMaxLength(int[] nums) {
        if (nums.length < 2) return nums.length;

        int[][] result = new int[nums.length][2]; // result[i][0] will store the max length of wiggle sequence in range [0,i]
        //[][0] represents the max length whlie the last is a decreasing sequence
        //[][1] represents the max length whlie the last is a increasing sequence
        for (int[] r: result) {
            Arrays.fill(r, 1);
        }

        int max = 1;
        for (int i=0; i<nums.length; i++) {
            for (int j=0; j<i; j++) {
                if (nums[i] < nums[j]) {
                    result[i][0] = Math.max(result[i][0], 1 + result[j][1]);
                }else if (nums[i] > nums[j]) {
                    result[i][1] = Math.max(result[i][1], 1 + result[j][0]);
                }
                max = Math.max(max, Math.max(result[i][0], result[i][1]));
            }
        }

        return max;
    }
}

Check out the description of this problem at LC 376.