Algorithm - Wiggle Subsequence(Greedy)

다용도리모콘·2021년 8월 28일
0

CodingTest

목록 보기
34/34

문제

A wiggle sequence is a sequence where 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 one element and a sequence with two non-equal elements are trivially wiggle sequences.

  • For example, [1, 7, 4, 9, 2, 5] is a wiggle sequence because the differences (6, -3, 5, -7, 3) alternate between positive and negative.
  • In contrast, [1, 4, 7, 2, 5] and [1, 7, 4, 5, 5] are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.
    A subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.
    Given an integer array nums, return the length of the longest wiggle subsequence of nums.

코드

function wiggleMaxLength(nums: number[]): number {
    let up = 1, down = 1;
    
    for(let i = 1; i < nums.length; i++) {
        if(nums[i] > nums[i-1]) up = down + 1;
        else if(nums[i] < nums[i-1]) down = up + 1;
    }
    return Math.max(up, down)
};

풀이

배열에서 앞 아이템과의 차가 차례대로 +, -가 지속 되도록 해야 하기 때문에 마지막 차가 +인 up과 -인 down을 두고 차가 +이면 -인 down에 1을 더한 값을 up에 넣고 차가 -이면 +인 up에 1을 더한 값을 down에 넣는다. 마지막까지 진행 했을 때 둘 중 큰 값을 리턴한다.

회고

이해는 했지만 다시 만났을 때 풀 수 있을지 의문인 문제.

0개의 댓글