// Given an array of Stock Prices of the day
// Calculate the Maximum Profits that could be made from single BUY-SELL trade,
// given that you must first BUY and then SELL
var stockPrices = [10, 7, 5, 8, 11, 9];
function minPrice( arr ){
var result = [];
if(Array.isArray(arr)){
result = arr.reduce((prev,curr,i)=>{return (prev&&prev.length>0)?prev[1]>=curr?[i,curr]:prev:[i,curr]},[]) ;
}
return result;
}
function maxPrice(arr,minPrice){
minPrice = minPrice || [];
var result =[];
if( Array.isArray(arr)){
var startIndex = minPrice[0] || 0;
result = arr.slice(startIndex).reduce((prev,curr,i)=>{
if( prev&&prev.length>0){
if(prev[1]<curr){
return[startIndex+i,curr];
} else{
return prev;
}
} else {
return [startIndex+i,curr];
}
},[]);
}
return result;
}
console.log(minPrice(stockPrices));
console.log(maxPrice(stockPrices,minPrice(stockPrices)));
var minPrice = minPrice(stockPrices);
var maxPrice = maxPrice(stockPrices,minPrice);
console.log("Max Profit : ", maxPrice[1] - minPrice[1] );
console.log(`Buying at ${minPrice[0]} and selling at ${maxPrice[0]}`)