DEV Community

Bernice Waweru
Bernice Waweru

Posted on • Edited on

1

Best Time to Buy and Sell Stock

Instructions

You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Example

Input: prices = [7,1,5,3,6,4]
Output: 5
Enter fullscreen mode Exit fullscreen mode

Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

Approach

To make a profit, you buy low and sell high. Therefore, we are looking for days where the price is low and when its high, we determine the difference and get maximum profit.

We can get a list of all the differences between prices on adjacent days using list comprehension then determine the max profit by finding the max between the prices.

def maxProfit(prices):
    diff_prices = [prices[i+1] - prices[i] for i in range(len(prices) - 1)]
    max_profit = 0
    current_profit = 0

    for profit in diff_prices:
        current_profit += profit
        if current_profit < profit:
            current_profit = profit
        max_profit = max(max_profit, current_profit)
    return max_profit

Enter fullscreen mode Exit fullscreen mode

Approach 2

We will use two pointers, left and right, where the right is at left+1 to get the differences and update the pointers. Whenever we encounter a new minimum we will automatically update the left pointer to that value.

Python Implementation.

 def maxProfit(self, prices: List[int]) -> int:
        maximum_profit = 0
        left = 0
        right = left+1
        while right < len(prices):
            if prices[right] > prices[left]:
                profit = prices[right]- prices[left]
                maximum_profit = max(profit,maximum_profit)
                right +=1
            else:
                left=right
                right +=1
        return maximum_profit
Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

DEV shines when you're signed in, unlocking a customized experience with features like dark mode!

Okay