Best Time to Buy and Sell Stock

Dhanaraj S
2 min readAug 31, 2021

Problem:

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

Input: prices = [7,1,5,3,6,4]
Output: 5
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.

Example 2:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.

Constraints:

  • 1 <= prices.length <= 105
  • 0 <= prices[i] <= 104

Approach 1:

Naive approach

Iterate over the entire array for each stock you currently bought, check if a future product you buy will earn something greater than the profit that yiu have in your hand.

Time: O(n²)

Space:O(1)

Approach 2:

More optimized solution

Iterate through the array single time. While iterating update the lowest element , if current element is less than lowest element found so far. Else update the variable profit, if the difference of current element- lowest elements so far , is greater than the profit so far.

Time :O(N)

Space: O(1)

--

--

Dhanaraj S

Tech-Enthusiast, Coder,Explorer,Geeky,Software Engineer |A piece of code delivers everything that you need. The world is all about codes.