You are given an integer array prices representing the daily price history of a stock, where prices[i] is the stock price on the ith day.
A smooth descent period of a stock consists of one or more contiguous days such that the price on each day is lower than the price on the preceding day by exactly 1. The first day of the period is exempted from this rule.
Return the number of smooth descent periods.
Example 1:
Input: prices = [3,2,1,4] Output: 7 Explanation: There are 7 smooth descent periods: [3], [2], [1], [4], [3,2], [2,1], and [3,2,1] Note that a period with one day is a smooth descent period by the definition.
Example 2:
Input: prices = [8,6,7,7] Output: 4 Explanation: There are 4 smooth descent periods: [8], [6], [7], and [7] Note that [8,6] is not a smooth descent period as 8 - 6 ≠ 1.
Example 3:
Input: prices = [1] Output: 1 Explanation: There is 1 smooth descent period: [1]
Constraints:
1 <= prices.length <= 1051 <= prices[i] <= 105This approach uses a stack to efficiently manage and track data as we process it. Stacks are last-in, first-out (LIFO) data structures that allow us to handle nested or hierarchical data effectively, such as the problem of parsing or evaluating expressions.
This C solution uses a custom stack implementation to evaluate a simple postfix expression. The stack is used to store operands, and operators are applied to the operands popped from the stack. The result is pushed back onto the stack. The final result is obtained by popping the stack after all operations are done.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), Space Complexity: O(n), where n is the length of the expression.
This approach utilizes recursion to evaluate the expression. Recursive functions are a profound way to break down complex problems into simpler instances of the same problem. Here, recursion helps by breaking the expression into parts that can be independently processed.
This C solution uses a recursive function to evaluate expressions. The function continuously evaluates parts of the expression by calling itself. This makes it a direct, elegant solution for nested or compound expressions.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), Space Complexity: O(n), where n is the depth of the recursion, potentially bound by the length of the expression.
| Approach | Complexity |
|---|---|
| Approach 1: Using a Stack | Time Complexity: O(n), Space Complexity: O(n), where n is the length of the expression. |
| Approach 2: Recursive Evaluation | Time Complexity: O(n), Space Complexity: O(n), where n is the depth of the recursion, potentially bound by the length of the expression. |
Sliding Window: Best Time to Buy and Sell Stock - Leetcode 121 - Python • NeetCode • 848,276 views views
Watch 9 more video solutions →Practice Number of Smooth Descent Periods of a Stock with our built-in code editor and test cases.
Practice on FleetCode