짬뽕얼큰하게의 맨땅에 헤딩 :: Longest Strictly Increasing or Strictly Decreasing Subarray

Leetcode Problem:

Summary

  • Find the length of the longest strictly increasing or decreasing subarray in a given array of integers.

Approach

  • The solution uses a dynamic programming approach
  • It maintains two variables, inc and dec, to track the length of the longest increasing and decreasing subarrays ending at the current position
  • The maximum length between these two subarrays is updated at each step.

Complexity

  • O(n), where n is the length of the input array
  • This is because the solution iterates through the array once.

Explain

  • The solution starts by initializing three variables: inc, dec, and ans
  • inc and dec are used to track the length of the longest increasing and decreasing subarrays ending at the current position, respectively
  • ans is used to store the maximum length of these subarrays
  • The solution then iterates through the array, updating inc and dec based on whether the current element is greater than or less than the previous element
  • If the current element is equal to the previous element, inc and dec are reset to 1
  • At each step, the solution updates ans to be the maximum of its current value and the maximum of inc and dec
  • Finally, the solution returns ans, which represents the length of the longest strictly increasing or decreasing subarray in the input array.

Solution Code:


class Solution {
public:
    int longestMonotonicSubarray(vector& nums) {
        int inc = 1;
        int dec = 1;
        int ans = 1;
        for(int i = 1 ; i < nums.size(); i++){
            if (nums[i-1] < nums[i]){
                inc++;
                dec = 1;
            }else if (nums[i-1] > nums[i]){
                inc = 1;
                dec++;
            } else{
                dec = 1;
                inc = 1;
            }
            
            ans = max(ans, max(inc, dec));
        }
        return ans;
    }
};

'알고리즘' 카테고리의 다른 글

Sort an Array  (0) 2025.02.04
Sort the Jumbled Numbers  (0) 2025.02.04
Sort Array by Increasing Frequency  (0) 2025.02.03
Sort the People  (0) 2025.02.03
Build a Matrix With Conditions  (0) 2025.02.03
블로그 이미지

짬뽕얼큰하게

,