Best Time to Buy and Sell Stock #121

ยท

2 min read

Check the problem statement on leetcode

Intuition

  1. You can not sell first and buy later. So it will remove all the cases where you need to check the difference from previous values

  2. You only have to make 1 trade

  3. You only need to find the difference bw the lowest and the next big value.

Sudo code

buy_day = 0 
sell_day = 1
max_profit = 0

while(sell_day < total_days){
    if(prices[buy_day] < prices[sell_day]){
        max_profit = max(
                          prices[buy_day] < prices[sell_day] ,
                          max_profit
                        )
    }else{
        buy_day = sell_day
    }
    sell_day++
}
return max_profit

Flow breakdown

Our goal is to find 2 points with the maximum height difference

The way to achieve it is to check if

  1. The selling point is > buy point

    • calculate the profit and compare it with the previous max_profit
  2. Else if the selling point is < buy point

    • update buy point to selling point.

This way we can iterate full array and reach the end and result will be max_profit

Code

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
let buy_day = 0 
let sell_day = 1
let total_days = prices.length
let max_profit = 0

while(sell_day < total_days){
    if(prices[buy_day] < prices[sell_day]){
        let profit = prices[sell_day] - prices[buy_day]
        max_profit = Math.max(profit,max_profit)
    }else{
        buy_day = sell_day
    }
    sell_day++
}
return max_profit
};
ย