Last active
October 15, 2017 01:58
-
-
Save jialinhuang00/3469e54a0c6536d6012f3cc1c586c2fe to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*----------------------------------------------------------------------------- | |
1.apply what we learn to find to minimun and maximum stock price | |
2.remember that the sell price is later than the buy price | |
NOTE: The first function I wrote was too simple to cover the situations | |
the reference used at the second function is from UdemyCourse: LearningAlgorithmsInJavascriptFromScratch | |
-----------------------------------------------------------------------------*/ | |
function maxStockProfit(priceArr) { | |
var priceArrCopied = Array.prototype.slice.call(priceArr); | |
var priceSorted = priceArr.sort((a, b) => { | |
return a - b; | |
}); | |
var highOrder = priceArrCopied.indexOf(priceSorted[priceSorted.length - 1]); | |
var lowOrder = priceArrCopied.indexOf(priceSorted[0]); | |
if (lowOrder > highOrder) return -1; | |
else return priceSorted[priceSorted.length - 1] - priceSorted[0]; | |
} | |
maxStockProfit([10, 18, 4, 5, 9, 6, 16, 12]); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function maxStockProfit2(priceArr) { | |
var maxProfit = -1, | |
temProfit, | |
sellPrice = 0, | |
buyPrice = 0, | |
r, | |
keepChanging = true; | |
for (r = 0; r < priceArr.length; r++) { | |
if (keepChanging) { | |
buyPrice = priceArr[r]; | |
} | |
sellPrice = priceArr[r + 1]; | |
if (sellPrice < buyPrice) { | |
keepChanging = true; | |
} else { | |
temProfit = sellPrice - buyPrice; | |
if (temProfit > maxProfit) { | |
maxProfit = temProfit; | |
} | |
keepChanging = false; | |
} | |
} | |
return maxProfit; | |
} | |
maxStockProfit2([10, 18, 4, 5, 9, 6, 16, 12]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment