Skip to content

Instantly share code, notes, and snippets.

@javi-aire
Created April 6, 2020 02:34
Show Gist options
  • Save javi-aire/268f6f98d30819478a3c2623ae52a494 to your computer and use it in GitHub Desktop.
Save javi-aire/268f6f98d30819478a3c2623ae52a494 to your computer and use it in GitHub Desktop.
Problem 5/30 of LeetCode 30-day challenge
let maxProfit = function(prices) {
// two pointers -- buy & sell
let buy = 0;
let sell = 1;
let buyPrice = 0;
let sellPrice = 0;
let price = 0;
while(sell < prices.length) {
if(prices[buy] < prices[sell]) {
// if the buy price is less than sell price
// set the corresponding prices then evaluate
// the next value after the current sell price
buyPrice = prices[buy];
sellPrice = prices[sell];
if(sellPrice > prices[sell+1] || prices[sell+1] === undefined){
// if the current sell price is higher than the next price
// or if we are at the end of the array
// complete a transaction
price += (sellPrice - buyPrice);
// set buy to the current sell,
// and sell to the next price
buy = sell;
sell = sell + 1;
} else {
// if the next price is higher,
// move the pointer to that price and reevaluate
sell++;
}
} else {
// else, move the pointers up one position
buy++;
sell++;
}
}
return price;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment