Skip to content

Instantly share code, notes, and snippets.

@kylejeske
Created October 18, 2019 14:57
Show Gist options
  • Save kylejeske/22e0ae9dbfb709e8e0a74cff1af0b859 to your computer and use it in GitHub Desktop.
Save kylejeske/22e0ae9dbfb709e8e0a74cff1af0b859 to your computer and use it in GitHub Desktop.
Using points within a subset to find max/min and profits from sale of a stock
/**
// using built-in functions
*/
function findMaxStockProfit(arr1) {
if (arr1.length < 2) {
return 0;
}
let arr1Min = Math.min(...arr1);
let subset = arr1.slice(arr1.indexOf(arr1Min));
// these two calls to math.min, math.max on subset
// hide the loop that is being done.
let numberBuy = Math.max(...subset);
let numberSell = Math.min(...subset);
let numberProfit = numberBuy - numberSell;
return numberProfit;
}
console.log(findMaxStockProfit([7,1,5,3,6,4]));
/**
// no built-in functions.
// 1. We have to find the min. number in the list
// 2. We have to find the max. number in the last, after the position of min.
// 3. no same day. and buy before you sell.
*/
function findMaxStockProfit(arr) {
// need a larger sample size. 1 day wont work.
if (arr.length < 2) {
return 0;
}
// set current min. and current max.
let profit = 0;
let minPos = 0;
let maxPos = 0;
let maxSoFar = arr[0];
let minSoFar = arr[0];
for(let i=0, x=1; i < arr.length; i++, x=i+1) {
// capture the minimum amount.
let currentPrice = arr[i];
let nextdayPrice = arr[x];
// subproblem1: is my current price cheaper than tomorrow
// is my currentPrice greater than my cheapest price?
// and, if so, is my nextdayPrice any cheaper?
// (if the min price is greater than todays price, todays price is cheaper)
if (minSoFar > nextdayPrice) {
// yes
// update the least price to reflect this one
minSoFar = nextdayPrice;
minPos = x;
}
// means we found our min. after we found our max.
if (minPos > maxPos) {
maxSoFar = currentPrice;
maxPos = i;
}
// if our max is less than current, we just found our new max.
if (currentPrice > maxSoFar) {
maxSoFar = currentPrice;
}
}
// Profit = How much it cost me - How much I sold it for.
// (This should be positive, not always though)
profit = ( maxSoFar - minSoFar );
// no negative profits today.
return (profit > 0)
? profit
: 0
;
}
console.log(findMaxStockProfit([7,1,5,3,6,4]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment