mediumArraysPattern: Observation and Iteration
Alternate Price Variations Solution
Problem Statement
You are given an array of integers `price` representing daily stock prices. Determine if it's possible to make the prices fluctuate by checking if every day's price is either higher or lower than the previous day's price, and the higher and lower prices alternate.
Examples
Example 1:
Input:{"price":[132435]}
Output:true
Explanation: Prices fluctuate as per the given conditions: 1 (lower), 3 (higher), 2 (lower), 4 (higher), 3 (lower), 5 (higher)
Example 2:
Input:{"price":[12345]}
Output:false
Explanation: Prices do not fluctuate as per the given conditions: the prices are consistently higher each day, not alternating
Constraints
- The input array will have a length between 2 and 1000.
- The input array will contain only integers between 1 and 10000.
Time: O(n) Space: O(1)
A more efficient approach would involve using a single pass through the array to compare each pair of consecutive prices, keeping track of the differences and checking if they alternate, resulting in a time complexity of O(n). This can be achieved by iterating through the array and using a variable to track the sign of the previous difference.
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
No solution code is currently loaded.
Complete this code in the workspace editor.
