Buying And Selling Position Stock Change With Maximum Profit
Buying And Selling Position Stock Change with Maximum Profit
by Hilarius Doren
HTML
<div>
Function To Calculate Stock Exchange to get Maximum Profit with position to buying and position to selling
</div>
JavaScript
const maxProfit = function(prices) {
let maxProfit = 0;
let min = prices[0];
let minPos = 0;
let maxPos = 0;
if (prices.length < 2){
return 0;
}
for(let i = 1; i < prices.length; i++) {
const tMin = min;
const tMax = maxProfit;
min = Math.min(prices[i], min);
if (min < tMin){
console.log('pos min: '+i);
minPos = i;
}
maxProfit = Math.max(maxProfit, prices[i] - min);
if (maxProfit > tMax){
console.log('pos max: '+i);
maxPos = i;
}
}
return [{'position_buying': minPos,'position_selling' : maxPos,'max_profit':maxProfit}];
};
//console.log(maxProfit([7,1,5,3,6,4]));
console.log(maxProfit([7]));