This content originally appeared on DEV Community and was authored by Julian
Tried to solve another question from leetcode involing buy and selling a stock at a specific price. The details are outlined below.
Need some guidance because the code dosen't work but i'm sure my logic is correct here. The comments outline what i am doing step by step for this question.
var maxProfit = function(prices) {
const buy = Math.min(prices); //finding the lowest value/ buy price
const index = prices.indexOf(buy); //get the index of the buy price
let temp = []; //temporary array to store possible sell prices
for (let i=index; i<prices.length-1; i++) {
if (prices[i] > prices[index]) { //iterate for every element in prices later than buy price
temp.push(prices[i]); //add the values to the temp array
}
}
const sell = Math.max(temp); //get the highest value in this temp array
const profit = sell-buy; //get profit
if (sell == null) {
return 0;
}
return profit;
};
This content originally appeared on DEV Community and was authored by Julian
Julian | Sciencx (2022-05-12T19:44:07+00:00) Best time to buy and sell stock. Retrieved from https://www.scien.cx/2022/05/12/best-time-to-buy-and-sell-stock/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.