Created
April 11, 2016 17:01
-
-
Save mmloveaa/58bb7822967b46cc8d27d956fa2683ab to your computer and use it in GitHub Desktop.
4-11 Patrick's solution
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 assert = require('assert'); | |
var assert = require('chai').assert; | |
describe('The findMaxProfit function', function() { | |
function findMaxProfit(stockPrices) { | |
// make sure we have at least 2 prices | |
if (stockPrices.length < 2) { | |
throw new Error('Getting a profit requires at least 2 prices'); | |
} | |
// we'll greedily update minPrice and maxProfit, so we initialize | |
// them to the first price and the first possible profit | |
var minPrice = stockPrices[0]; | |
var maxProfit = stockPrices[1] - stockPrices[0]; | |
// start at the second (index 1) time | |
// we can't sell at the first time, since we must buy first, | |
// and we can't buy and sell at the same time! | |
// if we started at index 0, we'd try to buy /and/ sell at time 0. | |
// this would give a profit of 0, which is a problem if our | |
// maxProfit is supposed to be /negative/--we'd return 0! | |
for (var i = 1; i < stockPrices.length; i++) { | |
var currentPrice = stockPrices[i]; | |
// see what our profit would be if we bought at the | |
// min price and sold at the current price | |
var potentialProfit = currentPrice - minPrice; | |
// update maxProfit if we can do better | |
maxProfit = Math.max(maxProfit, potentialProfit); | |
// update minPrice so it's always | |
// the lowest price we've seen so far | |
minPrice = Math.min(minPrice, currentPrice); | |
} | |
return maxProfit; | |
} | |
it('should return the max profit for an array of stock prices', function(){ | |
var arr = [9, 6, 7, 5, 10, 8]; | |
assert.equal(findMaxProfit(arr), 5); | |
}) | |
it('should be return a negative profit if values decrease over time', function () { | |
var arr = [10, 9, 8, 7, 6, 5] | |
assert.isBelow(findMaxProfit(arr), 0) | |
}); | |
it('should throw an error if input array length is less than 2', function () { | |
var arr = [1]; | |
assert.throws(function(){return findMaxProfit(arr)}, Error, 'Getting a profit requires at least 2 prices'); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment