Skip to content

Instantly share code, notes, and snippets.

@dorman99
Last active September 6, 2021 11:28
Show Gist options
  • Save dorman99/5aea17071abdc9ed00f882d10bee59bf to your computer and use it in GitHub Desktop.
Save dorman99/5aea17071abdc9ed00f882d10bee59bf to your computer and use it in GitHub Desktop.
Find Best Profit Trading
const fs = require("fs");
const file = fs.readFileSync("sample.txt", "utf-8");
const data = file.split(" ");
const findProfit = (buyStats) => {
let bestBuyTime = 0;
let bestProfit = 0;
let currentHodl = 0;
let currentValue = 0;
let lastHodl = 0;
for(let i = 0; i < buyStats.length; i++) {
if (i === 0) {
currentHodl = parseInt(buyStats[i]);
lastHodl = parseInt(buyStats[i]);
currentValue = currentHodl;
continue;
}
if (currentHodl > parseInt(buyStats[i]) && lastHodl < currentHodl) {
lastHodl = currentHodl;
currentHodl = parseInt(buyStats[i]);
bestBuyTime = i;
} else if (parseInt(buyStats[i]) > currentHodl && currentValue <= parseInt(buyStats[i])) {
currentValue = parseInt(buyStats[i]);
bestProfit = parseInt(buyStats[i]) - currentHodl;
}
}
if (bestProfit === 0) {
bestBuyTime = 0;
}
return {buyStats: buyStats, bestBuyTime, bestProfit, lastHodl};
}
const findProfits = data.map(el => findProfit(el));
const maxProfit = findProfits.reduce((total, obj2) => total + obj2.bestProfit, 0);
console.log({maxProfit})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment