Likou Brushing Notes: 376. Swing Sequence

Subject : 376. Swing sequence
If the difference between consecutive numbers alternates strictly between positive and negative numbers, the sequence of numbers is called a swing sequence. The first difference (if it exists) may be positive or negative. A sequence of less than two elements is also a wobble sequence.

For example, [1,7,4,9,2,5] is a swing sequence because the difference (6,-3,5,-7,3) is alternating between positive and negative. On the contrary, [1,4,7,2,5] and [1,7,4,5,5] are not swing sequences. The first sequence is because its first two differences are both positive. The second sequence It is because its last difference is zero.

Given an integer sequence, return the length of the longest subsequence as a wobble sequence. The sub-sequence is obtained by deleting some (or not deleting) elements from the original sequence, and the remaining elements maintain their original order.

Example 1:

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

Idea : It comes from the solution of the problem, I add my own understanding on the basis of its explanation

  • This question can be written using a greedy algorithm with O(n) time complexity and O(1) space complexity

  • count: count; prevdiff: maintain the previous state; diff: maintain the current state
    Insert picture description here

  • First of all, we draw the value and subscript of each element in such a graph, we can find that no matter in the process of rising or falling, as long as the number of elements exceeds two in the process of continuous rising (falling) , we only Just take two

  • So we only need to judge the previous state and the current state in the traversal.

  • In this way, in the process of continuous ascent (decline), we added twice according to the above steps

  • Although count++ is not given to the corresponding element as required by the title, it is also an algorithm to see the essence of the title.

Source code :

class Solution {
    
    
public:
    int wiggleMaxLength(vector<int>& nums) {
    
    
        int n = nums.size();

        if(n < 2){
    
    
            return n;
        }
        int prevdiff = nums[1] - nums[0];
        int count = prevdiff != 0 ? 2 : 1;
        for (int i = 2; i < n; i++) {
    
    
            int diff = nums[i] - nums[i - 1];
            if ((diff > 0 && prevdiff <= 0) || (diff < 0 && prevdiff >= 0)) {
    
    
                count++;
                prevdiff = diff;
            }
        }
        return count;
    }
};

Guess you like

Origin blog.csdn.net/qq_45914759/article/details/109314292