Sliding Window Problem: Given an array where the element at the index i
represents the price of a stock on day i
, find the maximum profit that you can gain by buying the stock once and then selling it.
I wonder if this can be solved most easily without the sliding window pattern:
def max_profit(prices):
min_price = float('inf')
for i in range(len(prices)):
min_price = min(min_price, prices[i])
prices[i] = prices[i] - min_price
return max(prices)
The potential downside is that it modifies the input. I often wonder whether a given problem encourages this or discourages this, and I wonder if adding that guidance to each problem would improve the course
Course: Grokking Coding Interview Patterns in Python - Learn Interactively
Lesson: Best Time to Buy and Sell Stock