![]() |
The stock span problem involves determining the consecutive days before each day where the stock price was less than or equal to the current day’s price. This algorithm efficiently calculates the stock spans using a stack-based approach, iterating through the prices array and maintaining a stack of indices representing previous days. The resulting span array indicates the span of each day’s stock price relative to previous days. Below are the approaches to solve the Stock Span problem using JavaScript Table of Content Using stackThis JavaScript function efficiently calculates the stock span for each day in an array of stock prices using a stack-based approach. It iterates through the prices array, maintaining a stack of indices representing previous days. For each day, it compares the current price with the previous ones stored in the stack, popping elements until finding a price less than the current day. The resulting span array represents the number of consecutive days before the current day with prices less than or equal to the current day’s price. Example: The code below shows the Stock Span problem using JavaScript using stack.
Output [ 1, 1, 1, 2, 1, 4, 6 ] Time Complexity: O(n), where n is the number of elements in the prices array. Space Complexity: O(n) since we use an additional stack to store indices. Using ArrayThis JavaScript function calculates the stock span for each day in an array of stock prices. It iterates through the prices array, comparing each price with the previous ones to determine the span. The resulting spans array represents the number of consecutive days before the current day with prices less than or equal to the current day’s price. Example: The code below shows Stock Span problem using JavaScript Using Array.
Output [ 1, 1, 1, 2, 1, 4, 6 ] Time complexity: O(n^2) Space complexity: O(n) Using dynamic programmingSince the same subproblems are called again, this problem has the Overlapping Subproblems property. S0, the recomputations of the same subproblems can be avoided by constructing a temporary array to store already calculated answers
Below is the implementation of the above approach:
Output 1 1 2 4 5 1 Time Complexity: O(N) Auxiliary Space: O(N) |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 16 |