2110. Number of Smooth Descent Periods of a Stock #2539
-
|
Topics: You are given an integer array 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 Return the number of smooth descent periods. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We need to count contiguous subarrays where each element decreases by exactly 1 from the previous element. Let me break down the solution approach. Approach:
Let's implement this solution in PHP: 2110. Number of Smooth Descent Periods of a Stock <?php
/**
* @param Integer[] $prices
* @return Integer
*/
function getDescentPeriods($prices) {
$n = count($prices);
if ($n == 0) return 0;
$total = 1; // Start with first day
$current = 1; // Length of current smooth descent ending at current position
for ($i = 1; $i < $n; $i++) {
if ($prices[$i] == $prices[$i - 1] - 1) {
// Continue the smooth descent
$current++;
} else {
// Start a new descent
$current = 1;
}
// Add all periods ending at current position
$total += $current;
}
return $total;
}
// Test cases
echo getDescentPeriods([3, 2, 1, 4]) . "\n"; // Output: 7
echo getDescentPeriods([8, 6, 7, 7]) . "\n"; // Output: 4
echo getDescentPeriods([1]) . "\n"; // Output: 1
?>Explanation:
|
Beta Was this translation helpful? Give feedback.
We need to count contiguous subarrays where each element decreases by exactly 1 from the previous element. Let me break down the solution approach.
Approach:
Let's implement this solution in PHP: 2110. Number of Smooth Descent Periods of a Stock