AMAZON Coding Question β Solved
In this new stock prediction game launched on Amazon Games, Player 1 provides Player 2 with stock market data for n consecutive days, representing Amazon's stock prices on each day, represented by the array stockData.
The rules of the game are as follows:
1. Player 1 will tell Player 2 a specific day number i (where 1 β€ i β€ n).
2. Player 2 has to find the nearest day j (1 β€ j β€ n, j β i) in the past or future on which the stock price was lower than on the given day, i.e., stockData[j] < stockData[i].
3. If there is more than one such j, then Player 2 must choose the one with the smallest day number.
4. If no such day j exists, the answer for that query is -1.
Given q queries in the array queries, the task is to find the answer for each queries[i] in the queries and return a list of answers corresponding to each query.
Example:
n = 10
stockData = [5, 6, 8, 4, 9, 10, 8, 3, 6, 4]
queries = [6, 5, 4]
- On day 6, the stock price is 10. Both days 5 and 7 have lower prices (9 and 8 respectively). Choose day 5 because it's earlier.
- On day 5, the stock price is 9. Day 4 has a lower price of 4.
- On day 4, the stock price is 4. The only lower price is on day 8 (3).
Thus, the output is [5, 4, 8].
Function Description:
Complete the function `predictAnswer` in the editor below.
`predictAnswer` has the following parameters:
- int stockData[n]: An integer array where each element represents the stock price on day i+1 (0-based indexing).
- int queries[q]: An array where each element is a query day number (1-based indexing).
Return:
- int[q]: An array of integers where each value at index i is the answer to queries[i], as per the game rules.
Constraints:
- 1 β€ n β€ 10^5
- 1 β€ stockData[i] β€ 10^9
- 1 β€ q β€ 10^5
- 1 β€ queries[j] β€ n
Asked in:
AMAZON