educative.io

Best time to buy and sell stock

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 :slight_smile:


Course: Grokking Coding Interview Patterns in Python - Learn Interactively
Lesson: Best Time to Buy and Sell Stock

1 Like

Hello @Isaac_Haseley,

The problem can definitely be solved without using the sliding window pattern just like you did. There are always more than 1 correct solutions to a single problem. And as for your statement regarding your solution modifying the input data.

You’re absolutely right; whether to modify the input array is a significant consideration and can depend on the specific requirements and constraints of the problem at hand.

We really appreciate your feedbacks and suggestions as they help in further improve and add more implementation strategies to the problems. We’ll carefully review your suggestion on adding constraint about modifying the input data in the Grokking courses. Feel free to share further suggestions and feedback. We’d be happy to help. Thanks!

Happy learning!