Problem Statement: Given an array of prices of stocks on different days, Need to find which days are the best for buying and selling the stocks.
funciton bestTimeToSellAndBuyCost(arr){}
const arr = [7,1,5,3,6,4]
bestTimeToSellAndBuyCost(arr)
This problem can be solved by looping
the array by taking two variables one is
min
(To find out the min element) which is initially assigned to the first element(arr[0]
) of the array and the second variable will beprofit
which is initially assigned to0
Initialize
cost
variable and assignmin - arr[i]
Take the max value from
profit
andcost
and assign it toprofit
Compare
min
andarr[i]
and assign min value tomin
function bestTimeToSellAndBuyCost(arr) {
let min = arr[0];
let profit = 0;
for (let i = 1; i < arr.length; i++) {
const cost = arr[i] - min;
profit = Math.max(profit, cost);
min = Math.min(arr[i], min);
}
return profit;
}
Thank you and have a great day :)