The stock_prices table stores one price record per row. Put the rows in order by record_date, breaking ties by id. A row is a local maximum when its price is strictly greater than the price of the row immediately before it and the price of the row immediately after it in that order.
Write a query that returns every local maximum.
Input Table(s)
stock_prices (primary key id)
| Column | Type | Meaning |
|---|
id | INT | Primary key. Breaks ties between rows that share a record_date. |
record_date | DATE | Date of the price record. NOT NULL. |
price | DECIMAL(10,2) | Recorded price. NOT NULL. |
Output Contract
-
Columns, in this order:
id
,
record_date
,
price
.
-
One row per local maximum, with the values exactly as stored (no rounding).
-
Sort by
record_date
ascending, then
id
ascending.
Example
stock_prices
| id | record_date | price |
|---|
| 1 | 2024-02-01 | 50 |
| 2 | 2024-02-02 | 55 |
| 3 | 2024-02-03 | 60 |
| 4 | 2024-02-04 | 58 |
| 5 | 2024-02-05 | 58 |
| 6 | 2024-02-06 | 62 |
| 7 | 2024-02-07 | 59 |
Expected output
| id | record_date | price |
|---|
| 3 | 2024-02-03 | 60 |
| 6 | 2024-02-06 | 62 |
Row 3 (60) is higher than row 2 (55) and row 4 (58). Row 5 (58) is not a local maximum because 58 is not strictly greater than the 58 in row 4. Row 6 (62) is higher than row 5 (58) and row 7 (59).
Constraints and Clarifications
-
The table has 1 to 10,000 rows.
-
Several rows can share a
record_date
. Within a date, the row with the smaller
id
comes first, and neighbors run across date boundaries: the row before the first row of a date is the last row of the previous date.
-
price
is a non-negative decimal with up to 2 decimal places. Neither
record_date
nor
price
is ever NULL.
-
The first and last rows in the order have no neighbor on one side, so they are never local maxima. A table with 1 or 2 rows returns no rows.
-
A tie with either neighbor disqualifies a row, because the comparison is strict.