DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Best Time To Buy Stock

Solution 1:

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    let minPrice = prices[0];
    let profit = 0;
    for(let i=0; i<prices.length; i++){
        if(prices[i] < minPrice){
            minPrice = prices[i];
        }else if (prices[i] - minPrice > profit){
            profit = prices[i] - minPrice;
        }
    }
    return profit;
}

Enter fullscreen mode Exit fullscreen mode

Solution 2 :

var maxProfit = function(prices) {
    let buy = prices[0]
    let profit = 0
    for (let price of prices) {
        if (price < buy) {
            buy = price
        }
        profit = Math.max(price - buy, profit)
    }
    return profit
};

Enter fullscreen mode Exit fullscreen mode

Best Time to Buy and Sell Stock II -

Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Total profit is 4 + 3 = 7.

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function (prices) {
  let left = 0;
  let profit = 0;

  for (let i = 0; i < prices.length; i++) {
    if (prices[i] > prices[left]) {
      let currentProfit = prices[i] - prices[left];
      profit = currentProfit + profit;
      left++;
    } else {
      left = i;
    }
  }

  return profit;
};

Enter fullscreen mode Exit fullscreen mode

Top comments (0)