![]() |
Given an array of numbers, our task is to find the length of the longest continuous subarray where the numbers are strictly decreasing. Example: Input: Below are the approaches to Find the length of the longest continuous decreasing subarray: Table of Content Iterative ApproachThe code initializes maxLength and currentLength. It iterates through the array, incrementing currentLength if the current element is less than the previous one; otherwise, it updates maxLength with the max of maxLength and currentLength, and resets currentLength to 1 for a new subarray. Finally, it returns maxLength, representing the length of the longest decreasing subarray. Example: The example below shows how to Find the length of the longest continuous decreasing subarray using Iterative Approach.
Output 4 Time Complexity: O(n), where n is the size of the input array. Auxiliary Space: O(1), which means it requires a constant amount of extra space. Dynamic Programming ApproachInitialize an array dp of the same length as the input array. Each element dp[i] will be initially set to 1. Iterate through the array starting from the second element. For each element at index i, compare it with the previous element. If the current element is less than the previous element, extend the longest decreasing subarray ending at index i by setting dp[i] = dp[i – 1] + 1. If current ≥ previous, it marks the beginning of a new decreasing subarray, setting dp[i] to 1. Then, after the loop, the maximum value in dp denotes the longest decreasing subarray length, returned as the result. Example: The example below shows how to Find the length of the longest continuous decreasing subarray using Dynamic Programming Approach.
Output 5 Time Complexity: O(n), where n is the size of the input array. Auxiliary Space: O(n), where n is the size of the input array. Using Single Pass Approach with a Counter VariableThis single-pass approach iterates through the array, updating a counter for the current decreasing sequence length. It tracks the maximum length encountered, resetting when a non-decreasing element is found, ensuring efficient identification of the longest continuous decreasing subarray. Example:
Output The length of the longest continuous decreasing subarray is: 6 |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 17 |