mediumArraysPattern: Basic Traversal
Maximize Price Difference Solution
Problem Statement
You are given an array of integers `prices` representing daily stock prices. Find the maximum possible difference between any two elements in the array, with the condition that the element representing the selling price must come after the element representing the buying price.
Examples
Example 1:
Input:{"prices":[715364]}
Output:5
Explanation: Buy at price 1 and sell at price 6, resulting in a return of 5
Constraints
- The input array will have at least 2 elements.
- The input array will contain only positive integers.
- The selling price must be greater than the buying price.
Time: O(n) Space: O(1)
The optimized approach involves iterating through the array once to find the maximum return. This approach has a linear time complexity and is efficient for large inputs. It can be implemented using a single loop to keep track of the minimum price and the maximum return seen so far.
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
def max_return(prices):
if len(prices) < 2:
return 0
min_price = prices[0]
max_return = 0
for i in range(1, len(prices)):
if prices[i] < min_price:
min_price = prices[i]
elif prices[i] - min_price > max_return:
max_return = prices[i] - min_price
return max_return