Created
April 18, 2015 20:46
-
-
Save adamblank/3d37f4ab0b71d0b0dc8f 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
var stock_prices = [15,14,11,10,8,6,5,2,1];//[10,11,12,15,8,9,10,14,11];//[10, 9, 8, 10, 13, 11, 9, 10, 15]; | |
var max_and_min = []; | |
var i = stock_prices.length - 1; | |
for (i; i >= 0; i--) { | |
if (max_and_min.length && (max_and_min[0].min == null || max_and_min[0].min > stock_prices[i])) { | |
max_and_min[0].min = stock_prices[i]; | |
} | |
if (!max_and_min.length || max_and_min[0].max < stock_prices[i]) { | |
max_and_min.unshift({ | |
max: stock_prices[i], | |
min: null | |
}); | |
} | |
} | |
var most_profit_idx = -1; | |
var max_profit = null; | |
var temp_profit; | |
for (i=0; i < max_and_min.length; i++) { | |
if (max_and_min[i].min === null) { | |
continue; | |
} | |
temp_profit = max_and_min[i].max - max_and_min[i].min; | |
if (max_profit === null || max_profit < temp_profit) { | |
max_profit = temp_profit; | |
} | |
} | |
console.log(max_and_min.length); | |
console.log(max_profit); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment