Skip to content

Instantly share code, notes, and snippets.

@TomaQ
Created July 3, 2018 03:26
Show Gist options
  • Save TomaQ/5cc454184bc7ae9937488dd23aaf9f14 to your computer and use it in GitHub Desktop.
Save TomaQ/5cc454184bc7ae9937488dd23aaf9f14 to your computer and use it in GitHub Desktop.
// Write a function that returns the maximum returns
// given a sequence of prices.
const stockPrices1 = [10, 7, 5, 8, 11, 9];
const stockPrices2 = [3, 7, 5, 13, 1, 8];
const stockPrices3 = [88, 4, 12, 3, 2, 1];
const stockPrices4 = [12, 16, 3, 2, 8, 7];
function getMaxProfit(prices) {
//Set the inial range
var maxReturns = prices[1] - prices[0];
for(var i = 0; i < prices.length -1; i++) {
for(var j = i+1; j < prices.length; j++) {
//i is the buying price and j is the selling price
var range = prices[j] - prices[i];
//Check if the range is greater than the current range
if(range > maxReturns){
maxReturns = range;
}
}
}
console.log(maxReturns);
}
getMaxProfit(stockPrices1); // 6
getMaxProfit(stockPrices2); // 10
getMaxProfit(stockPrices3); // 8
getMaxProfit(stockPrices4); // 6
//Since we are trying to find the gains from buying and selling 'stock' you have to buy first and then sell, this is why j = i + 1. Then you can just compare the numbers.
//The runtime though for this is O(n^2) since we are looking at a starting buying price (n-1) and looking at all possible selling prices (n-1)
function getMaxProfitInNTime(prices) {
//Set the default price
var maxReturns = prices[1] - prices[0];
//Get the lowest buy price
var minPrice = prices[0];
for(var i = 1; i < prices.length; i++) {
//Find the range of the current price and the minimum (so far) price
var range = prices[i] - minPrice;
//Check dat $$$
if(range > maxReturns)
maxReturns = range;
//Update the lowest price we've seen
if(minPrice > prices[i])
minPrice = prices[i];
}
console.log(maxReturns);
}
getMaxProfitInNTime(stockPrices1); // 6
getMaxProfitInNTime(stockPrices2); // 10
getMaxProfitInNTime(stockPrices3); // 8
getMaxProfitInNTime(stockPrices4); // 6
//In this we get the profit in O(n) cause after doing it in O(n^2) I remember doing a problem similar to this before (that I think you sent me lol)
//Basically set the inital values of the range and minimum price
//Start the loop at 1 (since we are using the index as our selling price) and check if the range is greater than the current max range
//If so, update the max range and after check if the minimum price is the lowest we've seen
//We have to check the range first before we update the minimum price since i-i would equal 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment